【问题标题】:CGSize Coding/DecodingCGSize 编码/解码
【发布时间】:2019-07-24 18:24:02
【问题描述】:

我想在 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

我理解 Encoder 是一个协议,我们应该使用哪个 Encoder/Decoder 类?

【问题讨论】:

  • 是否有理由在将size 存储到dictionary 之前对其进行编码?如果dictionary类型为[String: CGSize],则可以直接dictionary["size"] = size
  • 嗯,CGSize 确认到 Codable/plist 了吗?因为我还需要将此字典存储为 plist 并可选择将其发送到服务器。

标签: ios swift swift4 codable decodable


【解决方案1】:

正如你已经提到的,你不能直接使用Encoder,因为它是一个协议。另外,你做的不对,尺寸本身(CGSize没有encode方法,负责编码的是编码器。

假设dictionary 类型是[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)

如您所见,我们可以使用JSONEncoderJSONDecoder 来实现它。请记住,我们能够做到这一点是因为 CGSizeCodable


此外,您可以查看Using Codables for Persisting Custom Objects in UserDefaults;虽然它可能与您的问题没有直接关系,但我描述了如何处理任何类似的情况,这可以让您更清楚。

【讨论】:

  • CGSize 和 CGRect 现在是否可以在 Swift 中编码,它们可以保存在 plist 文件或字典中并可以传输到服务器?
  • @DeepakSharma 您可以检查developer.apple.com/documentation/coregraphics/cgsize 关系部分-“符合”,您会注意到它同时符合EncodableDecodable (Codable)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-13
  • 2013-04-06
  • 2017-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多