在 Objective-C 中,您可以要求一个类和属性的附加协议(protocol)实现:
@property (nonatomic) UIViewController<UISplitViewDelegate> *viewController;
这在 Swift 中可能吗?从文档来看,您似乎只能需要一个类或一个协议(protocol)。
最佳答案
实际上有两种方法可以在 Swift 中实现这一点:
使用空的“幻影”协议(protocol)。创建一个空协议(protocol)并使
UIViewController
符合它。这是最“Swift”的方法,安全且动态(不需要在编译时指定类)。protocol _UIViewControllerType {} extension UIViewController: _UIViewControllerType {} class MyClass { weak var viewController: protocol<UISplitViewControllerDelegate, _UIViewControllerType>? }
你也可以为这个类型声明一个
typealias
(只是为了减少代码困惑)。class MyClass { typealias ViewControllerType = protocol<UISplitViewControllerDelegate, _UIViewControllerType> weak var viewController: ViewControllerType? }
使用通用约束。如 fnc12 所述和 Konstantin Koval .这是安全的,但不允许您在运行时“交换” View Controller 实例。
class MyClass<T: UIViewController where T: UISplitViewControllerDelegate> { weak var viewController: T? }
我希望下一个 Swift 版本添加一种方法来指定这两个约束,而无需使用“幻像协议(protocol)”...
typealias ViewControllerType = UIViewController: UISplitViewControllerDelegate // wish
关于swift - 在 Swift 属性中要求协议(protocol)和类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24859053/