My structure does not conform to protocol 'Decodable' / 'Encodable'

旧时模样 提交于 2020-06-28 08:07:19

问题


I was trying to use Codable to save my data from the app I am creating but when I put Codable into my structure I keep getting the error:

Type 'ReminderGroups' does not conform to protocol 'Decodable'

and

Type 'ReminderGroups' does not conform to protocol 'Encodable'

struct ReminderGroups: Codable {
    var contentsArray: [ReminderItem] = []
    var reminderName: String = ""
    var reminderItem: UIImage = #imageLiteral(resourceName: "Folder")
}

回答1:


In order for a class or a struct to conform to a protocol, all properties of that class or struct must conform to the same protocol.

UIImage does not conform to Codable, so any class or struct that has properties of type UIImage won’t conform as well. You can replace the image with image data or the image’s base64 representation (as String).

I’ll show you the first option. I suppose you don’t want to write those if lets every time, so let’s add two little extensions to UIImage and Data that will speed up future conversions.

extension UIImage {
    var data: Data? {
        if let data = self.jpegData(compressionQuality: 1.0) {
            return data
        } else {
            return nil
        }
    }
}

extension Data {
    var image: UIImage? {
        if let image = UIImage(data: self) {
            return image
        } else {
            return nil
        }
    }
}

Change reminderItem’s type from UIImage to Data.

From now on, when you need to access the image, write something like imageView.image = reminderGroup.reminderItem.image. And when you need to save an instance of UIImage to reminderItem, write something like reminderGroup.reminderItem = image.data! (the bang operator (exclamation mark) is needed because the computed property data is optional).

Also make sure ReminderItem does conform to Codable. You didn’t provide the declaration of that type, so I can’t say whether it conforms of not.



来源:https://stackoverflow.com/questions/53252019/my-structure-does-not-conform-to-protocol-decodable-encodable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!