Ios CGSize编码/解码

Ios CGSize编码/解码,ios,swift,swift4,codable,decodable,Ios,Swift,Swift4,Codable,Decodable,我想在Swift中对CGSize数据类型进行编码和解码,并将其存储在字典中,但找不到任何示例代码。我尝试了这个,但它给出了错误: let size = CGSize(width: Int(100), height: Int(50)) dictionary["size"] = try! size.encode(to: Encoder()) Error: 'Encoder' cannot be constructed because it has no accessible initializ

我想在Swift中对CGSize数据类型进行编码和解码,并将其存储在字典中,但找不到任何示例代码。我尝试了这个,但它给出了错误:

 let size = CGSize(width: Int(100), height: Int(50))
 dictionary["size"] = try! size.encode(to: Encoder())

Error: 'Encoder' cannot be constructed because it has no accessible initializers

我知道编码器是一个协议,我们应该使用哪个编码器/解码器类?

正如您已经提到的,您不能直接使用
编码器,因为它是一个协议。另外,您这样做不正确,大小本身(
CGSize
)没有
encode
方法,负责编码的是编码器

假设
字典
类型为
[String:Data]
,您可以这样做:

var dictionary: [String: Data] = [: ]
let size = CGSize(width: Int(100), height: Int(50))

let sizeData = try JSONEncoder().encode(size)
dictionary["size"] = sizeData
要检索它,请执行以下操作:

let storedData = dictionary["size"]
let storedSize = try JSONDecoder().decode(CGSize.self, from: storedData!)
print(storedSize)
如您所见,我们可以使用
jsonecoder
JSONDecoder
来实现它。请记住,我们之所以能够做到这一点,是因为
CGSize
Codable



此外,你可以检查;虽然这可能与您的问题没有直接关系,但我描述了如何处理任何类似的情况,这可以让您更加清楚。

在将其存储到
字典之前,是否有理由对
大小进行编码?如果
dictionary
类型是
[String:CGSize]
,您可以直接
dictionary[“size”]=size
。那么,CGSize是否确认为可编码/plist?因为我还需要将此词典存储为plist并可以选择将其发送到服务器。CGSize和CGRect现在是否可以在Swift中编码,它们是否可以保存在plist文件或词典中并可以传输到服务器?@DeepakSharma您可以检查关系部分-“符合”您会注意到它同时符合
可编码
可解码
可编码
)。