BetterCodable icon indicating copy to clipboard operation
BetterCodable copied to clipboard

protocol CodableEnumeration for enum

Open zengxianshu opened this issue 3 years ago • 0 comments

Thank you for your code 👍。 The following code also works on my project, If you think it's useful, this package feels like a good home for it 🤝。

protocol CodableEnumeration: RawRepresentable, Codable where RawValue: Codable {
    static var defaultCase: Self { get }
}

extension CodableEnumeration {
    public init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        do {
            let decoded = try container.decode(RawValue.self)
            self = Self.init(rawValue: decoded) ?? Self.defaultCase
        } catch {
            self = Self.defaultCase
        }
    }
    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(rawValue)
    }
}

Usage:

enum FreeType: Int, CodableEnumeration {
        
    case normal = 1
    case free = 2
    
    static var defaultCase: Self { .normal }
}

let type: FreeType?

zengxianshu avatar Jul 19 '22 06:07 zengxianshu