what is 'where self' in protocol extension

Mini2008 picture Mini2008 · Sep 3, 2017 · Viewed 25.5k times · Source

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.

Answer

Brandon picture Brandon · Sep 3, 2017

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.