简体   繁体   中英

Does not conform to protocol Decodable

I have the following code which represents a Hockey Stick and some information about it. I have an issue where the stick isn't conforming to Decodable. I understand that every type used in the struct needs to also be codeable, and they are. For some reason however the "var conditions" line causes the error that I am unsure how to fix. Thank you!

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

The value type of your conditions dictionary is (StickCondition, String?) , which is a tuple. Tuples are not Decodable / Encodable , and you cannot make them conform to protocols, so to fix this I recommend you make a new struct to replace the tuple like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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