We can implement our own logic when encoding/decoding objects. Imagine we have a JSON structure that provides the width and height of a rectangle, but we want to store that information in a CGSize
property.
let json: String = """
{
"width": 35,
"height": 25
}
"""
struct MyRectangle: Codable {
let size: CGSize
// 1
enum CodingKeys: String, CodingKey {
case height
case width
}
// 2
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
let width = try values.decode(Double.self, forKey: .width)
let height = try values.decode(Double.self, forKey: .height)
size = CGSize(width: width, height: height)
}
// 3
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(size.width, forKey: .width)
try container.encode(size.height, forKey: .height)
}
}
Continue reading
Access to all the content with our plans.
- Junior level content
- Senior level content
- Expert level content
- Extra content
- Question submissions
Monthly
Yearly
Be the first to comment