decodable
What is difference between optional and decodeIfPresent when using Decodable for JSON Parsing?
There’s a subtle, but important difference between these two lines of code: // Exhibit 1 foo = try container.decode(Int?.self, forKey: .foo) // Exhibit 2 foo = try container.decodeIfPresent(Int.self, forKey: .foo) Exhibit 1 will parse: { “foo”: null, “bar”: “something” } but not: { “bar”: “something” } while exhibit 2 will happily parse both. So in … Read more
How to use Any in Codable Type
Quantum Value First of all you can define a type that can be decoded both from a String and Int value. Here it is. enum QuantumValue: Decodable { case int(Int), string(String) init(from decoder: Decoder) throws { if let int = try? decoder.singleValueContainer().decode(Int.self) { self = .int(int) return } if let string = try? decoder.singleValueContainer().decode(String.self) { … Read more
Swift 4 Decodable with keys not known until decoding time
The key is in how you define the CodingKeys property. While it’s most commonly an enum it can be anything that conforms to the CodingKey protocol. And to make dynamic keys, you can call a static function: struct Category: Decodable { struct Detail: Decodable { var category: String var trailerPrice: String var isFavorite: Bool? var … Read more
Custom Swift Encoder/Decoder for the Strings Resource Format
A bit late to the party here but I feel this might be helpful/informative to others given the question high vote count. (But I won’t really get into the actual usefulness of such code in practice—please check the comments above for that.) Unfortunately, given the coding stack flexibility and type-safeness, implementing a new encoding and … Read more
Codable class does not conform to protocol Decodable
The compiler cannot synthesise the required init(from:) method due to the weak reference, so you need to write it yourself. class Bookmark: Codable { weak var publication: Publication? var indexPath: [Int] var locationInText = 0 private enum CodingKeys: String, CodingKey { case indexPath case locationInText } init(publication: Publication?, indexPath: [Int]) { self.publication = publication self.indexPath … Read more