11

我想创建一个具有某种类型并且符合协议的属性,我会在 Objective-C 中这样做:

@property (nonatomic) UIViewController<CustomProtocol> *controller;

我正在寻找的是指定属性可以使用 UIViewController 类型的对象设置,该对象也符合 CustomProtocol,以便清楚基类是什么。我知道我可能只使用一个短类存根来获得相同的结果,即

class CustomViewController : UIViewController, CustomProtocol {}

但这似乎不是最干净的方法。

4

2 回答 2

11

现在可以使用内置组合来实现:

var children = [UIViewController & NavigationScrollable]()

于 2017-11-02T17:50:08.863 回答
8

我想不出用 Swift 表达这一点的好方法。类型的语法是:

类型 → 数组类型 | 字典类型 | 函数类型 | 类型标识符 | 元组类型 | 可选类型 | 隐式展开可选类型 | 协议组合类型 | 元型

您正在寻找的是一种也接受基类的协议组合类型。协议组合类型protocol<Proto1, Proto2, Proto3, …&gt;。)但是,目前这是不可能的。

允许具有相关类型要求的协议具有指定所需基类和所需协议的类型别名,但这些也要求在编译时知道类型,因此这对您来说不太可能是一个可行的选择。

如果你真的喜欢它,你可以用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>
}
于 2015-04-26T18:38:14.120 回答