相关疑难解决方法(0)

声明符合协议的类数组

让我们说我已经创建了这个协议和几个类

import UIKit

protocol ControllerConstructorProtocol {
    class func construct() -> UIViewController?
}

class MyConstructor: ControllerConstructorProtocol {
    class func construct() -> UIViewController? {
        return UIViewController()
    }
}

class MyOtherConstructor: ControllerConstructorProtocol {
    class func construct() -> UIViewController? {
        return UITableViewController(style: .Grouped)
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我想声明一个包含符合这种协议的对象类的数组.我怎么声明呢?理想情况下,我希望编译器检查数组是否正确填充(在编译时),而不是在运行时自己检查(运行时)as.

这是我尝试过没有成功:(

  1. 这会导致编译错误:

    '任何对象没有名为'construct'的成员

    var array = [
        MyConstructor.self,
        MyOtherConstructor.self,
    ]
    
    var controller = array[0].construct() // << ERROR here
    
    Run Code Online (Sandbox Code Playgroud)
  2. 写这个更糟糕,因为类本身不符合协议(他们的实例)

    类型'MyConstructor.Type'不符合协议'ControllerConstructorProtocol'

    var array: Array<ControllerConstructorProtocol> = [
        MyConstructor.self, // << ERROR here
        MyOtherConstructor.self,
    ]
    
    Run Code Online (Sandbox Code Playgroud)

编辑2016/04/23:在Swift 2.2(Xcode 7.3)中,可以编写 …

swift

8
推荐指数
1
解决办法
5127
查看次数

标签 统计

swift ×1