Swift&;核心数据:编码和解码自己类型的数组
这是我第一次尝试用Swift和核心数据对数据进行编码和解码。我正在努力对自己的数据类型的数组进行编码和解码,所有这些数组都遵循特定的协议 这是我的结构,它包含Swift&;核心数据:编码和解码自己类型的数组,swift,core-data,Swift,Core Data,这是我第一次尝试用Swift和核心数据对数据进行编码和解码。我正在努力对自己的数据类型的数组进行编码和解码,所有这些数组都遵循特定的协议 这是我的结构,它包含[Instrument]数组,其中Instrument是一个由三个结构实现的协议,它们分别命名为工具,驱动程序,和适配器: struct Instruments: Codable { // Telling me: Type 'Instruments' does not confirm to protocol 'Decodable' and
[Instrument]
数组,其中Instrument
是一个由三个结构实现的协议,它们分别命名为工具
,驱动程序
,和适配器
:
struct Instruments: Codable { // Telling me: Type 'Instruments' does not confirm to protocol 'Decodable' and 'Encodable'
var instruments: [Instrument]
var categories: [InstrumentCategory]
var instrumentCategories: [String: [Instrument]] {
Dictionary(
grouping: instruments,
by: { $0.category }
)
}
...
}
这就是我的仪器
协议的样子:
protocol Instrument: Codable {
var id: String { get }
var name: String { get set }
var category: String { get set }
var isFavorite: Bool { get set }
var errorMessages: [String]? { get set }
mutating func isValid() -> Bool
}
这就是遵循仪器
协议的其中一个结构的样子(驱动程序
和适配器
看起来非常相似):
编译器已经在Instruments
中告诉我:
-类型“仪器”不符合协议“可解码”
--协议要求初始化类型为“Decodable”的“init(from:)”
--无法自动合成“可解码”,因为“[Instrument]”不符合“可解码”
编码相同:
-类型“Instruments”不符合协议“Encodable”
--协议需要类型为“Encodable”的函数“encode(to:)”
--无法自动合成“Encodable”,因为“[Instrument]”不符合“Encodable”
如果在我的instruments
结构中,对变量instruments
和categories
使用enum CodingKeys:CodingKey
实现这些函数,编译器会遇到数组问题:
enum CodingKeys: CodingKey {
case instruments, categories
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
instruments = try container.decode([Instrument].self, forKey: .instruments) // Compiler error: Value of protocol type 'Instrument' cannot conform to 'Decodable'; only struct/enum/class types can conform to protocols
categories = try container.decode([InstrumentCategory].self, forKey: categories) // Compiler error: Cannot convert value of type '[InstrumentCategory]' to expected argument type 'Instruments.CodingKeys'
}
这就是我完全陷入困境的地方。您无法对协议进行编码或解码<代码>可编码需要具体类型。这正是只有struct/enum/class类型才能符合协议的错误消息的含义。谢谢,@vadian。将尝试为这三种具体类型添加switch语句。
enum CodingKeys: CodingKey {
case instruments, categories
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
instruments = try container.decode([Instrument].self, forKey: .instruments) // Compiler error: Value of protocol type 'Instrument' cannot conform to 'Decodable'; only struct/enum/class types can conform to protocols
categories = try container.decode([InstrumentCategory].self, forKey: categories) // Compiler error: Cannot convert value of type '[InstrumentCategory]' to expected argument type 'Instruments.CodingKeys'
}