首页 > 解决方案 > 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
    }
}

标签: iosswift

解决方案


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

推荐阅读