【问题标题】:Custom Struct: Type does not conform to protocol 'Decodable'自定义结构:类型不符合协议“可解码”
【发布时间】:2020-08-16 06:33:05
【问题描述】:

我希望能够将Custom-struct 保存到UserDefaults,但为此我需要将它保存为Codable.. 我这样尝试过:

struct Wishlist: Codable {
var name: String
var image: UIImage
var wishData: [Wish]
var color: UIColor
var textColor: UIColor
var index: Int
}

但这给了我这个error

类型“愿望清单”不符合协议“可解码”

这是我的Class Wish,也许这就是问题所在:

class Wish: NSObject {
public var wishName : String?
public var checkedStatus : Bool?
public var wishLink : String?
public var wishPrice : String?
public var wishNote : String?
public var wishImage : UIImage?

init(withWishName name: String, link: String, price: String, note: String, image: UIImage, checked: Bool) {
    super.init()
    wishName = name
    checkedStatus = checked
    wishLink = link
    wishPrice = price
    wishNote = note
    wishImage = image
}
}

我在这里做错了什么??

【问题讨论】:

  • 而不是“结构愿望清单:可编码”。使其结构愿望清单:可解码。如果这不能解决问题,请让您的班级愿望:可编码或可解码,而不是 NSObject
  • 你的班级也必须实现 Codable 协议
  • 如果我将Codable 添加到Wish 我会在Wish 中得到与Wishlist 相同的错误
  • 不能解决问题。如果我使 Wish Codable 我得到这个错误:Type 'Wish' does not conform to protocol 'Decodable''super' members cannot be referenced in a root class
  • UIImageUIColor 都不符合 Codable。将UIImage 映射到DataUIColor 到十六进制字符串值或Double 的数组。并且从不将属性声明为可选,这些属性使用非可选值进行初始化。

标签: ios swift struct codable


【解决方案1】:

您需要让Wish 采用Codable

但因为UIImageUIColor 不是Codable,您必须按照Encoding and Decoding Custom Types 中所述手动实现它们:

struct Wishlist: Codable {
    var name: String
    var image: UIImage
    var wishes: [Wish]
    var color: UIColor
    var textColor: UIColor
    var index: Int

    enum CodingKeys: String, CodingKey {
        case name, image, wishData, color, textColor, index
    }

    init(name: String, image: UIImage, wishes: [Wish], color: UIColor, textColor: UIColor, index: Int) {
        self.name = name
        self.image = image
        self.wishes = wishes
        self.color = color
        self.textColor = textColor
        self.index = index
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)

        name = try values.decode(String.self, forKey: .name)
        wishes = try values.decode([Wish].self, forKey: .wishData)
        color = try values.decode(Color.self, forKey: .color).uiColor
        textColor = try values.decode(Color.self, forKey: .textColor).uiColor
        index = try values.decode(Int.self, forKey: .index)

        let data = try values.decode(Data.self, forKey: .image)
        guard let image = UIImage(data: data) else {
            throw DecodingError.dataCorruptedError(forKey: .image, in: values, debugDescription: "Invalid image data")
        }
        self.image = image
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)

        try container.encode(name, forKey: .name)
        try container.encode(wishes, forKey: .wishData)
        try container.encode(Color(uiColor: color), forKey: .color)
        try container.encode(Color(uiColor: textColor), forKey: .textColor)
        try container.encode(index, forKey: .index)
        try container.encode(image.pngData(), forKey: .image)
    }

}

struct Wish: Codable {
    public var name: String
    public var checkedStatus: Bool
    public var link: String
    public var price: String
    public var note: String
    public var image: UIImage

    init(name: String, link: String, price: String, note: String, image: UIImage, checkedStatus: Bool) {
        self.name = name
        self.checkedStatus = checkedStatus
        self.link = link
        self.price = price
        self.note = note
        self.image = image
    }

    enum CodingKeys: String, CodingKey {
        case name, checkedStatus, link, price, note, image
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)

        name = try values.decode(String.self, forKey: .name)
        checkedStatus = try values.decode(Bool.self, forKey: .checkedStatus)
        link = try values.decode(String.self, forKey: .link)
        price = try values.decode(String.self, forKey: .price)
        note = try values.decode(String.self, forKey: .note)

        let data = try values.decode(Data.self, forKey: .image)
        guard let image = UIImage(data: data) else {
            throw DecodingError.dataCorruptedError(forKey: .image, in: values, debugDescription: "Invalid image data")
        }
        self.image = image
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)

        try container.encode(name, forKey: .name)
        try container.encode(checkedStatus, forKey: .checkedStatus)
        try container.encode(link, forKey: .link)
        try container.encode(price, forKey: .price)
        try container.encode(note, forKey: .note)
        try container.encode(image.pngData(), forKey: .image)
    }
}

我将使用它作为编码UIColor 对象的便捷方式:

struct Color: Codable {
    let red: CGFloat
    let green: CGFloat
    let blue: CGFloat
    let alpha: CGFloat

    init(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
        self.red = red
        self.green = green
        self.blue = blue
        self.alpha = alpha
    }

    init(uiColor: UIColor) {
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0

        uiColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)

        self.red = red
        self.green = green
        self.blue = blue
        self.alpha = alpha
    }

    var uiColor: UIColor { UIColor(red: red, green: green, blue: blue, alpha: alpha) }
}

注意,我做了一些不相关的更改:

  • 我做了这两个struct。除非必要,否则我不会引入引用类型(更不用说NSObject 子类)。

  • 我简化了一些属性名称。例如。在Wish 中,我们通常不会在属性名称中使用wish 前缀。我也不会在属性名称中使用“数据”,除非它实际上是 Data

  • 我更新了init 方法以使用标准命名约定。

【讨论】:

  • 这是一个 10/10 的答案。谢谢!很好的解释,非常感谢你的帮助:)
【解决方案2】:

在您的情况下,您应该添加 CodingKeys 枚举,而不是使用 UIColorUIImage 数据类型。我之前遇到过同样的错误,但后来我意识到 CodingKey 与结构不匹配,也没有 non-codable 数据类型。只需将数据类型更改为您的自定义可编码对象。

错误的例子:

public struct DtClip: Codable {

    // MARK: Properties
    public var video: String?
    public var preview: String?
    public var clip: String?
    public var trailer: Any?

    enum CodingKeys: String, CodingKey {
        case video = "video"
        case preview = "preview"
        case clip = "clip"
    }
}

从示例中我们知道trailer 还没有在codingKeys 中。您应该将所有道具添加到CodingKeys。并且Any 数据类型应更改为可编码数据类型,如StringIntTrailer(自定义可编码数据类型)。下面是正确的例子:

public struct DtClip: Codable {

    // MARK: Properties
    public var video: String?
    public var preview: String?
    public var clip: String?
    public var trailer: Trailer?

    enum CodingKeys: String, CodingKey {
        case video = "video"
        case preview = "preview"
        case clip = "clip"
        case trailer = "trailer"
    }
}

public struct Trailer: Codable {

    // MARK: Properties
    public var name: String?
    public var id: Int?

    enum CodingKeys: String, CodingKey {
       case name, url
    }
}

【讨论】:

    【解决方案3】:

    UIImage 不符合 Codable。您可以先将其转换为 Base64,然后将 that 存储在 UserDefaults

    【讨论】:

    • 或者,只需获取Data(无论如何,您都需要对其进行base64编码)并直接存储它并绕过手动base64编码。
    • @Rob 这里有几个建议,但你似乎对我在这里要做的事情有很好的理解。你能详细说明一下吗? :)
    猜你喜欢
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多