Swift中的批量初始化和协议

时间:2017-04-27 16:00:26

标签: swift swift3 swift-protocols

我有那些协议

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

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

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

我有课:

  • ClassAOneClassATwoClassAThree符合ProtocolA
  • ClassBOneClassBTwoClassBThree符合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数组作为输入,我希望将初始化对象数组作为输出。

1 个答案:

答案 0 :(得分:2)

是的,但结果是非常难看的IMO。 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.
    }
}