what is ‘where self’ in protocol extension

That syntax is: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-ID521 Consider: protocol Meh { func doSomething() } // Extend protocol Meh, where `Self` is of type `UIViewController` // func blah() will only exist for classes that inherit `UIViewController`. // In fact, this entire extension only exists for `UIViewController` subclasses. extension Meh where Self: UIViewController { func blah() { print(“Blah”) } func … Read more

Why can’t a get-only property requirement in a protocol be satisfied by a property which conforms?

There’s no real reason why this shouldn’t be possible, a read-only property requirement can be covariant, as returning a ConformsToB instance from a property typed as ProtocolB is perfectly legal. Swift just currently doesn’t support it. In order to do so, the compiler would have to generate a thunk between the protocol witness table and … Read more

Swift 2 Error using mutating function in Protocol extension “Cannot use mutating member on immutable value: ‘self’ is immutable

The problem is that, in the protocol you mark the function as mutating, which you need to do if you want to use the protocol on a struct. However, the self that is passed to testFunc is immutable (it’s a reference to a instance of the class) and that is tripping up the compiler. This … Read more

When to use `protocol` and `protocol: class` in Swift?

Swift 4 version AnyObject added to a protocol definition like this protocol FilterViewControllerDelegate: AnyObject { func didSearch(parameters:[String: String]?) } means that only a class will be able to conform to that protocol. So given this protocol FilterViewControllerDelegate: AnyObject { func didSearch(parameters:[String: String]?) } You will be able to write this class Foo: FilterViewControllerDelegate { func … Read more

How does one declare optional methods in a Swift protocol?

1. Using default implementations (preferred). protocol MyProtocol { func doSomething() } extension MyProtocol { func doSomething() { /* return a default value or just leave empty */ } } struct MyStruct: MyProtocol { /* no compile error */ } Advantages No Objective-C runtime is involved (well, no explicitly at least). This means you can conform … Read more