I saw so many examples with below format
extension Protocolname where Self: UIViewController
What is where Self
in protocol extension. I couldn't find the documentation on this.
Protocols let you describe what methods something should have, but don't provide the code inside. Extensions let you provide the code inside your methods, but only affect one data type – you can't add the method to lots of types at the same time.
An extension can extend an existing type to make it adopt one or more protocols. To add protocol conformance, you write the protocol names the same way as you write them for a class or structure: extension SomeType: SomeProtocol, AnotherProtocol { // implementation of protocol requirements goes here.
In Swift, a protocol defines a blueprint of methods or properties that can then be adopted by classes (or any other types). Here, Greet - name of the protocol. name - a gettable property.
In Swift, we can add new functionality to existing types. We can achieve this using an extension. We use the extension keyword to declare an extension. For example, // class definition class Temperature { ... } // extension of Temperature class extension Temperature { // add new methods }
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 foo() { print("Foo") } } class Foo : UIViewController, Meh { //This compiles and since Foo is a `UIViewController` subclass, it has access to all of `Meh` extension functions and `Meh` itself. IE: `doSomething, blah, foo`. func doSomething() { print("Do Something") } } class Obj : NSObject, Meh { //While this compiles, it won't have access to any of `Meh` extension functions. It only has access to `Meh.doSomething()`. func doSomething() { print("Do Something") } }
The below will give a compiler error because Obj doesn't have access to Meh extension functions.
let i = Obj() i.blah()
But the below will work.
let j = Foo() j.blah()
In other words, Meh.blah()
is only available to classes that are of type UIViewController
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With