gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 07:13:20 24 4
gpt4 key购买 nike

我有那些协议(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com