swift - 在 Swift 属性中要求协议(protocol)和类

标签 swift ios8

在 Objective-C 中,您可以要求一个类和属性的附加协议(protocol)实现:

@property (nonatomic) UIViewController<UISplitViewDelegate> *viewController;

这在 Swift 中可能吗?从文档来看,您似乎只能需要一个类或一个协议(protocol)。

最佳答案

实际上有两种方法可以在 Swift 中实现这一点:

  1. 使用空的“幻影”协议(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?
    }
    
  2. 使用通用约束。如 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/

相关文章:

ios - 本地化字符串在 UITests(快照)中始终为英文

ios - bool 比较或零比较更快吗?

ios - TableView 单元格启用编辑

swift - Firebase 删除后 UICollectionView 数据未删除

iphone - ios 模拟器在 xcode 6 中出现并带有 UDID

iphone - 在 Swift 中使用 shouldPerformSegueWithIdentifier( ) 方法

swift - 如何将 swift 类添加到我的框架 header ?

scroll - -webkit溢出滚动: touch; breaks in Apple's iOS8

IOS 8 - 导航栏按钮问题

ios - 以编程方式创建的动态 TableView Controller 在被不同的静态 TableView Controller 访问时未被调用