What is Protocol Oriented Programming in Swift? What added value does it bring?

Preface: POP and OOP are not mutually exclusive. They’re design paradigms that are greatly related. The primary aspect of POP over OOP is that is prefers composition over inheritance. There are several benefits to this. In large inheritance hierarchies, the ancestor classes tend to contain most of the (generalized) functionality, with the leaf subclasses making … Read more

How do I add different types conforming to a protocol with an associated type to a collection?

Protocols with type aliases cannot be used this way. Swift doesn’t have a way to talk directly about meta-types like ValidationRule or Array. You can only deal with instantiations like ValidationRule where… or Array<String>. With typealiases, there’s no way to get there directly. So we have to get there indirectly with type erasure. Swift has … Read more

How to pass one SwiftUI View as a variable to another View struct

To sum up everything I read here and the solution which worked for me: struct ContainerView<Content: View>: View { @ViewBuilder var content: Content var body: some View { content } } This not only allows you to put simple Views inside, but also, thanks to @ViewBuilder, use if-else and switch-case blocks: struct SimpleView: View { … Read more

Xcode 10.2 with Swift 5.0 compiler – protocol inheritance issue

You may be running into https://bugs.swift.org/browse/SR-10257 in the Swift 5.0 compiler. This would happen if you have at least three files: BasicViewController.swift SomeOtherFile.swift ExampleViewController.swift If SomeOtherFile.swift makes any calls to an AnyObject-typed value, you’re compiling in wholemodule mode, and the files are passed to the compiler in the above order (with SomeOtherFile.swift in the middle … Read more

How to define a protocol as a type for a @ObservedObject property?

Wrappers and stored properties are not allowed in swift protocols and extensions, at least for now. So I would go with the following approach mixing protocols, generics and classes… (all compilable and tested with Xcode 11.2 / iOS 13.2) // base model protocol protocol ItemViewModel: ObservableObject { var title: String { get set } func … Read more

tech