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.