Skip to content

Instantly share code, notes, and snippets.

@algal
Created July 10, 2017 21:58
Show Gist options
  • Save algal/de7e046d819f92cbb4e0eed26f7a334b to your computer and use it in GitHub Desktop.
Save algal/de7e046d819f92cbb4e0eed26f7a334b to your computer and use it in GitHub Desktop.
CGRect Codable implementation
// known-good: Swift 4, in Xcode Version 9.0 beta 2 (9M137d)
// will be unnecessary once the language can auto-synthesize for this case, or
// when Apple's ships a Codable implementation for CoreGraphics struct types.
extension CGSize : Codable {
enum CodingKeys: String, CodingKey {
case width
case height
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(width,forKey:.width)
try container.encode(height,forKey:.height)
}
public init(from decoder:Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
width = try values.decode(CGFloat.self, forKey: .width)
height = try values.decode(CGFloat.self, forKey: .height)
}
}
extension CGPoint : Codable {
enum CodingKeys: String, CodingKey {
case x
case y
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(x,forKey:.x)
try container.encode(y,forKey:.y)
}
public init(from decoder:Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
x = try values.decode(CGFloat.self, forKey: .x)
y = try values.decode(CGFloat.self, forKey: .y)
}
}
extension CGRect : Codable {
enum CodingKeys: String, CodingKey {
case origin
case size
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(origin,forKey:.origin)
try container.encode(size,forKey:.size)
}
public init(from decoder:Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
origin = try values.decode(CGPoint.self, forKey: .origin)
size = try values.decode(CGSize.self, forKey: .size)
}
}
@algal
Copy link
Author

algal commented Oct 31, 2017

Warning. Currently it seems to me that:

  • Apple did ship a default Codable implementation for CGPoint, on iOS
  • Apple did ship a default Codable implementation for CGPoint, but not on macOS (?!)
  • it uses a different scheme than the one above

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment