[英]Swift Initialize struct based on typealias
我希望我的代码尽可能地可重用。 Writer
和JsonProperties
是定义相关对象所需的大量功能的协议。 JsonProperties
符合Codable
协议,但是我想通过一个Writer
来实现一个自定义的 Core Data 实现方法,问题是:
我可以通过 JsonProperties 的类型别名初始化实现Writer
协议的JsonProperties
吗?
现在我收到这个错误:
无法将类型“[Model]”的值转换为预期的参数类型“[Model.WriterType.Model]”
这是代码:
protocol Writer {
associatedtype Model: JsonProperties
...
init(in dataStack: DataStack)
}
struct GenericWriter<Model: JsonProperties>: Writer { ... }
protocol JsonProperties: Codable {
associatedtype WriterType: Writer
...
}
struct ConversationProperties: JsonProperties {
typealias WriterType = GenericWriter<Self>
...
}
我正在寻找的实现,但得到的错误是:
func networkFetch<Model: JsonProperties>(type: Model.Type) -> AnyPublisher<Bool, Error> {
let writer = Model.WriterType(in: dataStack)
...
var objects = [Model]()
...
writer.insert(objects) <- Error here!
我猜这不是typealias
结构的init()
的正确实现。
您看到的问题源于您没有限制JsonProperties
WriterType
目前,它接受任何符合Writer
的WriterType
类型,不管它的Model
是什么。
您可能想要的是WriterType
类型使其Model
与符合JsonProperties
协议的类型相同 - 因此您需要对其进行约束:
protocol JsonProperties: Codable {
associatedtype WriterType: Writer where WriterType.Model == Self
}
insert
方法接受[Model]
,其中Model
是Writer
的关联类型。
writer
的类型为Model.WriterType
,其中WriterType
是Writer
,因此writer.insert
接受Model.WriterType.Model
。 这里,第一个Model
是networkFetch
的泛型参数,而第二个Model
是Writer
协议的关联类型。
但是,您已经创建了一个[Model]
。 这个Model
指的是networkFetch
的泛型参数,而不是关联的类型。
实际上不能保证您的通用参数Model
与Model.WriterTypeModel.Model
的类型相同。 例如,我可以这样做:
struct FooProperties: JsonProperties {
typealias WriterType = GenericWriter<ConversationProperties>
}
如果我将FooProperties.self
传递给networkFetch
,通用参数Model
将是FooProperties
,但Model.WriterType.Model
将是ConversationProperties
。
有很多方法可以解决这个问题。
WriterType
关联类型以首先禁止我创建FooProperties
:protocol JsonProperties: Codable {
associatedtype WriterType: Writer where WriterType.Model == Self
}
Model
:func networkFetch<Model: JsonProperties>(type: Model.Type) -> AnyPublisher<Bool, Error>
where Model.WriterType.Model == Model {
Model.WriterType.Model
数组代替(如果您要反序列化Model
类型的对象并将它们放入此数组中,这将不起作用)var objects = [Model.WriterType.Model]()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.