But Car.manufacturer is optional, so it makes sense to have a valid model, even if the received manufacturer doesn’t match one of the currently supported ones:
Unfortunately decoding this with JSONDecoder results in getting nil for the whole Car instead of just Car.manufacturer.
This can be solved by custom init(from:) of the Decodable protocol, but that’s a lot of boilerplate, especially when you have dozens of enums in your models.
This is where CodableNilOnFail comes in!
Usage
Just add the @NilOnFail property wrapper to your optional RawRepresentable properties.
struct Car: Codable, Equatable {
enum Manufacturer: String, Codable {
case toyota, volkswagen, ford, honda, generalMotors
}
@NilOnFail var manufacturer: Manufacturer?
var vin: String?
var owner: String?
}
CodableNilOnFail
Easy failable optional enum properties in Swift Codable.
Installation
You can add CodableNilOnFail to an Xcode project by adding it as a package dependency.
https://github.com/sochalewski/CodableNilOnFail
into the package repository URL text field.Why?
Consider the following data model:
Everything works perfectly if the received JSON matches the available
Manufacturer
enum values, like this:But
Car.manufacturer
is optional, so it makes sense to have a valid model, even if the received manufacturer doesn’t match one of the currently supported ones:Unfortunately decoding this with
JSONDecoder
results in gettingnil
for the wholeCar
instead of justCar.manufacturer
.This can be solved by custom
init(from:)
of theDecodable
protocol, but that’s a lot of boilerplate, especially when you have dozens of enums in your models.This is where CodableNilOnFail comes in!
Usage
Just add the
@NilOnFail
property wrapper to your optionalRawRepresentable
properties.Author
Piotr Sochalewski, sochalewski.github.io