首页 > 解决方案 > Swift & Core Data:编码和解码自己类型的数组

问题描述

这是我第一次尝试使用 Swift 和 Core Data 对数据进行编码和解码。我正在努力编码和解码自己的数据类型的数组,所有这些都遵循某种协议。

这是我的包含数组的结构[Instrument],其中Instrument是在三个结构中实现的协议,命名为ToolDriverAdapter

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 }
        )
    }
...
}

这就是我的Instrument协议的样子:

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
}

这就是遵循此Instrument协议的结构之一的样子(Driver并且Adapter看起来非常相似):

struct Tool: Instrument, Hashable, Codable, Identifiable, Comparable {
    let id = UUID().uuidString
    var name: String
    var category: String
    var isFavorite: Bool
    var profileType: String
    var profileSize: String
    var length: String?
    var driverCouplingId: Int?
    var set: String?
    var location: String?
    var comment: String?

    var errorMessages: [String]?

...
}

编译器已经告诉我Instruments: - 'Instruments' 类型不符合协议'Decodable - 协议需要使用'Decodable' 类型初始化'init(from:)' - 无法自动合成'Decodable',因为'[Instrument]'不符合“可解码”

编码也一样:-“仪器”类型不符合“可编码”协议--协议需要“可编码”类型的函数“编码(to:)”--不能自动合成“可编码”,因为“[仪器]”不符合“可编码”

如果我实现这些函数,使用enum CodingKeys: CodingKey变量instrumentscategories我的Instruments结构,编译器会遇到数组问题:

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'
    }

这是我完全卡住的地方。

标签: swiftcore-data

解决方案


推荐阅读