0

请看一下我的代码:

没有错误

struct Person: Codable {
    var name: String
    var age: Double
    var birthday: Date
    
    var selectedItem: Car
}

struct Car: Codable {
    var companyName: String
    var creationDate: Date
}

struct iPhone: Codable {
    var model: String
    var creationDate: Date
    var isScreenBroken: Bool = true
}

构建错误

struct Person: Codable { // "Type 'Person' does not conform to protocol 'Decodable'", "Type 'Person' does not conform to protocol 'Encodable'"
    var name: String
    var age: Double
    var birthday: Date
    
    var selectedItem: Codable // I've changed this line
}

struct Car: Codable {
    var companyName: String
    var creationDate: Date
}

struct iPhone: Codable {
    var model: String
    var creationDate: Date
    var isScreenBroken: Bool = true
}

类型“人”不符合协议“可解码”

类型“人”不符合协议“可编码”

我不明白为什么会这样。它知道selectedItem符合Encodable& Decodable

var selectedItem: Codable

我是 Swift 协议的新手,所以请在回答时尝试解释这里发生了什么。

谢谢!

4

1 回答 1

2

这里编译器的问题是,通常当一个类型被定义为符合时Codable,编译器会为您合成代码,以便Person在这种情况下符合协议。它通过为您创建一个实现init(from decoder: Decoder) throws和其中之一来做到这一点func encode(to encoder: Encoder) throws

但是,当您更改selectedItem为 type时Codable,编译器将无法再合成这些方法,因为它需要确切知道 type 的类型selectedItem必须正确生成代码的属性。

您需要在这里做的是使用泛型

struct Person<T: Codable>: Codable {
    var name: String
    var age: Double
    var birthday: Date

    var selectedItem: T
}

struct Car: Codable {
    var companyName: String
    var creationDate: Date
}

struct iPhone: Codable {
    var model: String
    var creationDate: Date
    var isScreenBroken: Bool = true
}

然后编译器又高兴了,你可以像这样使用它

let person = Person(name: "Joe", age: 40, birthday: date, selectedItem: Car(companyName: "Ford", creationDate: Date()))
于 2021-01-01T09:00:32.523 回答