-1

I want to encode and decode CGSize data type in Swift and store it in a Dictionary, but am not able to find any sample code how to do it. I tried this but it gives error:

 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

I understand Encoder is a protocol, which Encoder/Decoder class are we supposed to use?

Deepak Sharma
  • 5,577
  • 7
  • 55
  • 131
  • 1
    Is there a reason to encode `size` before storing it into `dictionary`? If `dictionary` type is `[String: CGSize]`, you could directly `dictionary["size"] = size`. – Ahmad F Jul 24 '19 at 18:39
  • Well, does CGSize confirm to Codable/plist? Because I also need to store this dictionary as plist & optionally send it to server. – Deepak Sharma Jul 24 '19 at 18:45

1 Answers1

1

As you already mentioned, you cannot directly use Encoder since it is a protocol. Also, you are doing it improperly, size itself (CGSize) does not has encode method, the responsible one to encode is the encoder.

Assuming that dictionary type is [String: Data], this is how you could do it:

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

let sizeData = try JSONEncoder().encode(size)
dictionary["size"] = sizeData

For retrieving it:

let storedData = dictionary["size"]
let storedSize = try JSONDecoder().decode(CGSize.self, from: storedData!)
print(storedSize)

As you can see, we can use JSONEncoder and JSONDecoder to achieve it. Keep in mind that we are able to do it because CGSize is Codable.


Furthermore, you could check Using Codables for Persisting Custom Objects in UserDefaults; Although It might be not directly related to your issue, I described how to deal with any similar case which could make it more clear to you.

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
  • Are CGSize & CGRect now Codable in Swift, that they can be saved in plist files or Dictionaries and can be transferred to server? – Deepak Sharma Jul 24 '19 at 19:00
  • 1
    @DeepakSharma you could check https://developer.apple.com/documentation/coregraphics/cgsize Relationship section - "conforms to" and you'll notice that it conforms for both `Encodable` and `Decodable` (`Codable`). – Ahmad F Jul 24 '19 at 19:27