Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/sochalewski/easycodable
Easy failable properties in Swift Codable.
https://github.com/sochalewski/easycodable
codable json swift
Last synced: about 2 months ago
JSON representation
Easy failable properties in Swift Codable.
- Host: GitHub
- URL: https://github.com/sochalewski/easycodable
- Owner: sochalewski
- License: mit
- Created: 2022-07-09T12:10:11.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2023-11-09T00:43:12.000Z (about 1 year ago)
- Last Synced: 2024-10-30T17:24:28.543Z (about 2 months ago)
- Topics: codable, json, swift
- Language: Swift
- Homepage:
- Size: 15.6 KB
- Stars: 3
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# EasyCodable
Easy failable optional enum properties in Swift Codable.
## Installation
You can add EasyCodable to an Xcode project by adding it as a package dependency.
1. From the **File** menu, select **Add Packages…**
2. Enter `https://github.com/sochalewski/EasyCodable` into the package repository URL text field.
3. Add the package to your app target.## Why?
Consider the following data model:
```swift
struct Car: Codable {
enum Manufacturer: String, Codable {
case toyota, volkswagen, ford, honda, generalMotors
}
var manufacturer: Manufacturer?
var vin: String?
var owner: String?
}
```Everything works perfectly if the received JSON matches the available `Manufacturer` enum values, like this:
```json
{
"manufacturer": "toyota",
"vin": "JT4RN67S0G0002845",
"owner": null
}
```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:
```json
{
"manufacturer": "tesla",
"vin": "5YJSA2DP8DFP22249",
"owner": "Elon Musk"
}
```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 EasyCodable comes in!
## Usage
Just add the `@EasyNil` property wrapper to your optional `RawRepresentable` properties.
```swift
struct Car: Codable, Equatable {
enum Manufacturer: String, Codable {
case toyota, volkswagen, ford, honda, generalMotors
}
@EasyNil var manufacturer: Manufacturer?
var vin: String?
var owner: String?
}
```## Author
Piotr Sochalewski, sochalewski.github.io