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

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

How to convert a date string with optional fractional seconds using Codable in Swift?

You can use two different date formatters (with and without fraction seconds) and create a custom DateDecodingStrategy. In case of failure when parsing the date returned by the API you can throw a DecodingError as suggested by @PauloMattos in comments: iOS 9, macOS 10.9, tvOS 9, watchOS 2, Xcode 9 or later The custom ISO8601 … 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 enum with default case in Swift 4

You can extend your Codable Type and assign a default value in case of failure: enum Type: String { case text, image, document, profile, sign, inputDate = “input_date”, inputText = “input_text” , inputNumber = “input_number”, inputOption = “input_option”, unknown } extension Type: Codable { public init(from decoder: Decoder) throws { self = try Type(rawValue: decoder.singleValueContainer().decode(RawValue.self)) … Read more

Using codable with value that is sometimes an Int and other times a String

struct GeneralProduct: Codable { var price: Double? var id: String? var name: String? private enum CodingKeys: String, CodingKey { case price = “p”, id = “i”, name = “n” } init(price: Double? = nil, id: String? = nil, name: String? = nil) { self.price = price self.id = id self.name = name } init(from decoder: … Read more

Encode nil value as null with JSONEncoder

Yes, but you’ll have to write your own encode(to:) implementation, you can’t use the auto-generated one. struct Foo: Codable { var string: String? = nil var number: Int = 1 func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(number, forKey: .number) try container.encode(string, forKey: .string) } } Encoding an optional directly … Read more

Using Decodable in Swift 4 with Inheritance

I believe in the case of inheritance you must implement Coding yourself. That is, you must specify CodingKeys and implement init(from:) and encode(to:) in both superclass and subclass. Per the WWDC video (around 49:28, pictured below), you must call super with the super encoder/decoder. required init(from decoder: Decoder) throws { // Get our container for … Read more