How to exclude properties from Swift Codable?

The list of keys to encode/decode is controlled by a type called CodingKeys (note the s at the end). The compiler can synthesize this for you but can always override that. Let’s say you want to exclude the property nickname from both encoding and decoding: struct Person: Codable { var firstName: String var lastName: String … Read more

How to decode a property with type of JSON dictionary in Swift [45] decodable protocol

With some inspiration from this gist I found, I wrote some extensions for UnkeyedDecodingContainer and KeyedDecodingContainer. You can find a link to my gist here. By using this code you can now decode any Array<Any> or Dictionary<String, Any> with the familiar syntax: let dictionary: [String: Any] = try container.decode([String: Any].self, forKey: key) or let array: … Read more

With JSONDecoder in Swift 4, can missing keys use a default value instead of having to be optional properties?

You can implement the init(from decoder: Decoder) method in your type instead of using the default implementation: class MyCodable: Codable { var name: String = “Default Appleseed” required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if let name = try container.decodeIfPresent(String.self, forKey: .name) { self.name = name } } } You … Read more