protocol AddsMoreCommands: class {
// Code
}
extension AddsMoreCommands where Self: UIViewController {
// Code
}
不使用扩展程序也可以实现这一点:
protocol AddsMoreCommands: UIViewController {
// code
}
这与下面的内容完全相同:
protocol AddsMoreCommands where Self: UIViewController {
// code
}
我通常使用第一种选项,如果约束条件是Self
,那么根据Swift文档中的推荐方式来实现。如果约束条件是其他诸如关联类型,则可以使用where
。
请注意,由于UIViewController
也是一个class
,因此此协议可用于实现弱引用属性(例如委托)。
已编辑2021/01/05:之前发布的解决方案有警告,我已将其删除并使用此解决方案,它不会产生任何警告。
AnyObject
而不是 class
。 protocol AddsMoreCommands: AnyObject where Self: UIViewController { // 代码 }
- dodgioprotocol AddsMoreCommands where Self : UIViewController {
// protocol stuff here
}
Xcode 9.1没有警告
AddsMoreCommands
的属性转换为UIViewController
,而我想避免这种情况... - heyfranktypealias AddsMoreCommandsViewController = UIViewController & AddsMoreCommands
。 - plu现在在Swift 5中,您可以通过以下方式实现:
protocol AddsMoreCommands: UIViewController {
/* ... */
}
相当方便。
self
而不是Self
:-( 非常感谢,现在可以了! - emrys57AnyObject
而不是class
-> https://docs.swift.org/swift-book/LanguageGuide/Protocols.html#ID281。但目前两个版本的行为都相同,没有弃用警告。 - heyfrankoverride var prefersStatusBarHidden
? - Chris Prince