我想不出用 Swift 表达这一点的好方法。类型的语法是:
类型 → 数组类型 | 字典类型 | 函数类型 | 类型标识符 | 元组类型 | 可选类型 | 隐式展开可选类型 | 协议组合类型 | 元型
您正在寻找的是一种也接受基类的协议组合类型。(协议组合类型是protocol<Proto1, Proto2, Proto3, …>
。)但是,目前这是不可能的。
允许具有相关类型要求的协议具有指定所需基类和所需协议的类型别名,但这些也要求在编译时知道类型,因此这对您来说不太可能是一个可行的选择。
如果你真的喜欢它,你可以用UIViewController
你使用的接口部分定义一个协议,使用扩展来增加一致性,然后使用protocol<UIViewControllerProtocol, CustomProtocol>
.
protocol UIViewControllerProtocol {
func isViewLoaded() -> Bool
var title: String? { get set }
// any other interesting property/method
}
extension UIViewController: UIViewControllerProtocol {}
class MyClass {
var controller: protocol<UIViewControllerProtocol, CustomProtocol>
}