Skip to content

Safely decode / fallback primitive type for Decodable

License

Notifications You must be signed in to change notification settings

Beyova/SafeDecoder

Repository files navigation

SafeDecoder

Travis CI Carthage Compatible SPM

SafeDecoder enhance the compatibility for Decodable.

Installation

Carthage

github "Beyova/SafeDecoder"

Usage

import SafeDecoder

Decode primitive type when acture json is String

class User: Codable {
	var id: Int
}
let decoder = SafeDecoder()
let data = try JSONSerialization.data(withJSONObject: ["id": "42"], options: [])
let result = try decoder.decode(User.self, from: data)

Decode String type when acture json is primitive

class User: Codable {
	var id: String
}
let decoder = SafeDecoder()
let data = try JSONSerialization.data(withJSONObject: ["id": 42], options: [])
let result = try decoder.decode(User.self, from: data)

Customize fallback value when decode fail

enum Gender: String, Codable {
    case unknown
    case male
    case female
}

struct User: Codable {
    let gender: Gender
    
    enum CodingKeys: String, FallbackCodingKey 
        case gender
        func fallbackValue() -> FallbackValue {
            switch self {
            case .gender: return (true, Gender.unknown)
            }
        }
    }
}
let decoder = JSONDecoder()
let data = try JSONSerialization.data(withJSONObject: [:], options: [])
let result = try decoder.decode(User.self, from: data)

About

Safely decode / fallback primitive type for Decodable

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages