How to require that a protocol can only be adopted by a specific class

后端 未结 4 1655
灰色年华
灰色年华 2021-02-01 00:13

I want this protocol:

protocol AddsMoreCommands {
     /* ... */
}

only to be adopted by classes that inherit from the class UIViewContro

4条回答
  •  情深已故
    2021-02-01 00:32

    This can also be achieved without an extension:

    protocol AddsMoreCommands: UIViewController {
        // code
    }
    

    Which is exactly the same as:

    protocol AddsMoreCommands where Self: UIViewController {
       // code
    }
    

    I usually use the first option, IIRC I read a while ago on the Swift docs that that is the recomended way when the constraint is Self, if is other constraint such as associate types is when where can be used.

    Notice that since UIViewController is a class too, this protocol can be implemented for weak properties such as delegates.

    EDITED 2021/01/05: Previous posted solution had a warning, I have removed it and use this one which does not produce any warning.

提交回复
热议问题