Swift 中的批量初始化和协议
Bulk initialisation and protocols in Swift
我有那些协议
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.
}
}
我有那些协议
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.
}
}