提问人:Meeshoo 提问时间:11/17/2023 更新时间:11/17/2023 访问量:37
Swift:实例化泛型类中的类型 <T> 实例
Swift: Instantiate type <T> instance in a generic class
问:
我想要一个泛型类 ClassA,其类型为 T 参数,该参数符合名为 ItemProtocol 的特定协议。我想在类中有一个 T 数组,但 T 实例的初始化不起作用。应该怎么做?
protocol ItemProtocol: Codable {
var itemId: String { get set }
var parameter2: String { get set }
var parameter3: String { get set }
}
struct Item: ItemProtocol {
var itemId: String
var parameter2: String
var parameter3: String
}
protocol AClassProtocol {
associatedtype ItemProtocol
func createItem() -> [ItemProtocol]
}
class ClassA<T: ItemProtocol>: AClassProtocol {
private lazy var items = [T]()
private func createItem() -> [T] {
let newItem = T(itemId: "someDummyID", //Compilation error here
parameter2: "ABC",
parameter3: "BCA")
items.append(newItem)
return items
}
}
答:
3赞
HangarRash
11/17/2023
#1
问题在于,它没有定义任何显式初始值设定项。如果将以下声明添加到:T
ItemProtocol
ItemProtocol
ItemProtocol
init(itemId: String, parameter2: String, parameter3: String)
加上这个,这条线:
let newItem = T(itemId: "someDummyID",
parameter2: "ABC",
parameter3: "BCA")
将按预期编译。
如果没有该添加,唯一可用的 via 是从您通过的协议中声明的。这被声明为触发有关丢失的错误的位置。init
ItemProtocol
init
Decodable
Codable
init
init(from: Decoder)
from
评论
0赞
Meeshoo
11/17/2023
太棒了,非常感谢!在创建这篇文章之前,我尝试了类似的东西,但我在协议扩展中添加了一个默认实现,这给我带来了其他问题。
评论