我的结构不符合协议“可解码” /“可编码” [英] My structure does not conform to protocol 'Decodable' / 'Encodable'
问题描述
我试图使用Codable从正在创建的应用程序中保存数据,但是当我将Codable放入我的结构时,我不断收到错误消息:
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:
类型'ReminderGroups'不符合协议'可解码'
Type 'ReminderGroups' does not conform to protocol 'Decodable'
and
类型'ReminderGroups'不符合协议'Encodable'
Type 'ReminderGroups' does not conform to protocol 'Encodable'
struct ReminderGroups: Codable {
var contentsArray: [ReminderItem] = []
var reminderName: String = ""
var reminderItem: UIImage = #imageLiteral(resourceName: "Folder")
}
推荐答案
为了使某个类或结构符合协议,该类或结构的所有属性必须符合同一协议。
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
不符合 Codable
,因此任何属性类型为 UIImage
的类或结构都不会也符合。您可以将图像替换为图像数据或图像的base64表示形式(如 String
)。
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
).
我将显示您是第一个选择。我想您不想每次写如果让
,那么让我们添加两个小的扩展名
到 UIImage
和 Data
可以加快未来的转换速度。
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
}
}
}
将 reminderItem
的类型从 UIImage
到 Data
。
从现在开始,在需要时要访问图像,请编写类似 imageView.image = hinterGroup.reminderItem.image
的内容。然后,当您需要将 UIImage
的实例保存到 reminderItem
时,编写类似 reminderGroup的内容。 hinterItem = image.data!
(需要bang运算符(感叹号),因为计算出的属性 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).
还要确保 ReminderItem
确实符合 Codable
。您没有提供该类型的声明,所以我不能说它是否符合。
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.
这篇关于我的结构不符合协议“可解码” /“可编码”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!