Swift’s JSONDecoder with multiple date formats in a JSON string?

Please try decoder configurated similarly to this: lazy var decoder: JSONDecoder = { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .custom({ (decoder) -> Date in let container = try decoder.singleValueContainer() let dateStr = try container.decode(String.self) // possible date strings: “2016-05-01”, “2016-07-04T17:37:21.119229Z”, “2018-05-20T15:00:00Z” let len = dateStr.count var date: Date? = nil if len == 10 { … Read more

Swift 4 Decodable – Dictionary with enum as key

The problem is that Dictionary‘s Codable conformance can currently only properly handle String and Int keys. For a dictionary with any other Key type (where that Key is Encodable/Decodable), it is encoded and decoded with an unkeyed container (JSON array) with alternating key values. Therefore when attempting to decode the JSON: {“dictionary”: {“enumValue”: “someString”}} into … Read more

How to conform UIImage to Codable?

Properly the easiest way is to just make the property Data instead of UIImage like this: public struct SomeImage: Codable { public let photo: Data public init(photo: UIImage) { self.photo = photo.pngData()! } } Deserialize the image: UIImage(data: instanceOfSomeImage.photo)!

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

Encode/Decode Array of Types conforming to protocol with JSONEncoder

The reason why your first example doesn’t compile (and your second crashes) is because protocols don’t conform to themselves – Tag is not a type that conforms to Codable, therefore neither is [Tag]. Therefore Article doesn’t get an auto-generated Codable conformance, as not all of its properties conform to Codable. Encoding and decoding only the … 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