繁体   English   中英

Swift 根据 typealias 初始化结构体

[英]Swift Initialize struct based on typealias

我希望我的代码尽可能地可重用。 WriterJsonProperties是定义相关对象所需的大量功能的协议。 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

目前,它接受任何符合WriterWriterType类型,不管它的Model是什么。

您可能想要的是WriterType类型使其Model与符合JsonProperties协议的类型相同 - 因此您需要对其进行约束:

protocol JsonProperties: Codable {
    associatedtype WriterType: Writer where WriterType.Model == Self
}

insert方法接受[Model] ,其中ModelWriter的关联类型。

writer的类型为Model.WriterType ,其中WriterTypeWriter ,因此writer.insert接受Model.WriterType.Model 这里,第一个ModelnetworkFetch的泛型参数,而第二个ModelWriter协议的关联类型。

但是,您已经创建了一个[Model] 这个Model指的是networkFetch的泛型参数,而不是关联的类型。

实际上不能保证您的通用参数ModelModel.WriterTypeModel.Model的类型相同。 例如,我可以这样做:

struct FooProperties: JsonProperties {
    typealias WriterType = GenericWriter<ConversationProperties>
}

如果我将FooProperties.self传递给networkFetch ,通用参数Model将是FooProperties ,但Model.WriterType.Model将是ConversationProperties

有很多方法可以解决这个问题。

  1. 您可以限制WriterType关联类型以首先禁止我创建FooProperties
protocol JsonProperties: Codable {
    associatedtype WriterType: Writer where WriterType.Model == Self
}
  1. 您可以约束通用参数Model
func networkFetch<Model: JsonProperties>(type: Model.Type) -> AnyPublisher<Bool, Error>
    where Model.WriterType.Model == Model {
  1. 您可以创建一个Model.WriterType.Model数组代替(如果您要反序列化Model类型的对象并将它们放入此数组中,这将不起作用)
var objects = [Model.WriterType.Model]()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM