我有那些协议
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数组作为输入,我希望将初始化对象数组作为输出。
答案 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.
}
}