繁体   English   中英

不符合协议可解码

[英]Does not conform to protocol Decodable

我有以下代码代表曲棍球棒和一些关于它的信息。 我有一个问题,棒不符合 Decodable。 我知道结构中使用的每种类型也需要是可编码的,而且它们是。 但是由于某种原因,“var conditions”行会导致我不确定如何修复的错误。 谢谢!

enum StickLocation: Int, Codable, Hashable, CaseIterable {
    case handle, mid, bottom
}

enum StickCondition: Int, Codable, Hashable, CaseIterable {
    case pristine, scuffed, damaged, broken
}

struct HockeyStick: Identifiable, Codable {
    var barcode: Int
    var brand: String
    var conditions: [StickLocation:(condition:StickCondition, note:String?)]    // Offending line
    var checkouts: [CheckoutInfo]
    var dateAdded: Date
    var dateRemoved: Date?

    // Conform to Identifiable.
    var id: Int {
        return self.barcode
    }

    // If the stick was never removed then its in service.
    var inService: Bool {
        return self.dateRemoved == nil
    }
}

您的conditions字典的值类型是(StickCondition, String?) ,它是一个元组。 元组不是Decodable / Encodable ,并且您不能使它们符合协议,因此要解决此问题,我建议您创建一个新结构来替换元组,如下所示:

enum StickLocation: Int, Codable, Hashable, CaseIterable {
    case handle, mid, bottom
}

enum StickCondition: Int, Codable, Hashable, CaseIterable {
    case pristine, scuffed, damaged, broken
}

struct StickConditionWithNote: Codable, Hashable {
    var condition: StickCondition
    var note: String?
}

struct HockeyStick: Identifiable, Codable {
    var barcode: Int
    var brand: String
    var conditions: [StickLocation: StickConditionWithNote]
    var checkouts: [CheckoutInfo]
    var dateAdded: Date
    var dateRemoved: Date?

    // Conform to Identifiable.
    var id: Int {
        return self.barcode
    }

    // If the stick was never removed then its in service.
    var inService: Bool {
        return self.dateRemoved == nil
    }
}

暂无
暂无

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

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