问题
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 let
s every time, so let’s add two little extension
s 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