Created
July 10, 2017 21:58
-
-
Save algal/de7e046d819f92cbb4e0eed26f7a334b to your computer and use it in GitHub Desktop.
CGRect Codable implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Warning. Currently it seems to me that:
Codable
implementation forCGPoint
, on iOSCodable
implementation forCGPoint
, but not on macOS (?!)