如何要求一个协议只能被一个特定的类采用

我要这个协议:

protocol AddsMoreCommands {
/* ... */
}

只能被继承自 UIViewController类的类采用。这一页告诉我,我可以通过写来指定它只被一个类(相对于结构)采用

protocol AddsMoreCommands: class {
}

但我看不出如何要求它只被某个特定的阶级采用。那一页之后谈到将 where子句添加到协议扩展以检查一致性,但我也看不出如何适应这一点。

extension AddsMoreCommands where /* what */ {
}

有办法吗? 谢谢!

28738 次浏览
protocol AddsMoreCommands: class {
// Code
}


extension AddsMoreCommands where Self: UIViewController {
// Code
}

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.

Because of an issue in the previous answer I ended up with this declaration:

protocol AddsMoreCommands where Self : UIViewController {
// protocol stuff here
}

no warnings in Xcode 9.1

Now in Swift 5 you can achieve this by:

protocol AddsMoreCommands: UIViewController {
/* ... */
}

Quite handy.