Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is 'where self' in protocol extension

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.

like image 316
Mini2008 Avatar asked Sep 02 '17 22:09

Mini2008


People also ask

What are protocol extensions?

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.

Can you extend a protocol?

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.

What is protocol in Swift with example?

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.

What is extension in Swift?

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 }


1 Answers

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.

like image 50
Brandon Avatar answered Oct 12 '22 04:10

Brandon