swift - Swift 中的批量初始化和协议(protocol)

标签 swift swift3 swift-protocols

我有那些协议(protocol)

protocol BaseProtocol: CustomStringConvertible {
   var aVar: Int? {get set}
}

protocol ProtocolA: BaseProtocol {
    init(number: Int)
}

protocol ProtocolB: BaseProtocol {
    init(number: Int, string: String)
}

我有课:

  • ClassAOne, ClassATwo, ClassAThree 符合ProtocolA
  • ClassBOne, ClassBTwo, ClassBThree 符合ProtocolB

所以我想要的是写一个批量初始化。这是我想要的示例:

let arrayOfClasses: [Any] = [ClassAOne.self, ClassATwo.self, ClassBThree.self, ClassAThree]

let number = 10
let text = "test"

let initializedObjects = arrayOfClasses.map { classType in
    // This code isn't compilable
    // If class type is a class which conform to ProtocolA - use simple init
    if let protocolA = classType as? ProtocolA {
        return ProtocolA.init(number: number)
    } 
    // If class type is a class which conform to ProtocolB - use longer init
    if let protocolB = classType as? ProtocolB {
        return ProtocolB.init(number: number, string: text)
    }
}

有可能吗? 基本上我有 Class.self 数组作为输入,我想有初始化对象数组作为输出。

最佳答案

是的,但在我看来,结果非常丑陋。 initializedObjects 必须是 [Any],这是一个可怕的类型(而且 Any? 可能会悄悄出现,这更糟糕).我真的建议只按类型拆分类,除非这会引起严重的头痛。也就是说,探索类型如何在 Swift 中工作是可能的,也是一种有益的探索。

let initializedObjects = arrayOfClasses.flatMap { classType -> Any? in
    switch classType {
    case let protocolA as ProtocolA.Type:
        return protocolA.init(number: number)

    case let protocolB as ProtocolB.Type:
        return protocolB.init(number: number, string: text)

    default:
        return nil // Or you could make this return `Any` and fatalError here.
    }
}

关于swift - Swift 中的批量初始化和协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43662654/

相关文章:

swift - 如何在 swift 3 中从 base64 获取字节数组?

javascript - 使用 JavaScriptCore 的 JSContext 时,如何在 JavaScript 中定义不需要特定顺序的类

ios - 使用未解析的标识符 'PhoneAuthProvider'

swift - 在扩展中重新声明成员*有时*会隐藏原始成员。为什么?

ios - 如何避免对两个不同的类使用具有相同方法的两个扩展

swift - 无法将类型 "AProtocol"的值转换为预期的参数类型协议(protocol)。

arrays - 使用 for 循环打印 Array 或 Set 的内容

ios - 限制几个文本字段的长度

swift - 如何回放录制的视频?

ios - 在 iOS 10 + Swift 3 中以编程方式在我的 WKWebView 上方添加一个 UILabel