Swod 4中的默认情况下的Codable枚举

Luc*_*lli 22 enums ios swift swift4 codable

我已定义enum如下:

enum Type: String, Codable {
    case text = "text"
    case image = "image"
    case document = "document"
    case profile = "profile"
    case sign = "sign"
    case inputDate = "input_date"
    case inputText = "input_text"
    case inputNumber = "input_number"
    case inputOption = "input_option"

    case unknown
}
Run Code Online (Sandbox Code Playgroud)

映射JSON字符串属性.自动序列化和反序列化工作正常,但我发现如果遇到不同的字符串,反序列化将失败.

是否可以定义一个unknown映射任何其他可用案例的案例?

这可能非常有用,因为这些数据来自RESTFul API,可能会在将来发生变化.

Leo*_*bus 63

您可以扩展Codable类型并在发生故障时分配默认值:

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)) ?? .unknown
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 反对解释其原因的评论将不胜感激,并将允许我修复和/或改进我的答案的问题。没有理由的否决是没有意义的 (4认同)
  • 这应该是公认的答案!完美的工作 (3认同)

nay*_*yem 8

您可以删除原始类型Type,并使未知大小写的案例处理关联的值。但这是有代价的。您以某种方式需要案例的原始值。从启发这个这个 SO回答我想出了这个优雅的解决你的问题。

为了能够存储原始值,我们将保留另一个枚举,但将其设为私有:

enum Type {
    case text
    case image
    case document
    case profile
    case sign
    case inputDate
    case inputText
    case inputNumber
    case inputOption
    case unknown(String)

    // Make this private
    private enum RawValues: String, Codable {
        case text = "text"
        case image = "image"
        case document = "document"
        case profile = "profile"
        case sign = "sign"
        case inputDate = "input_date"
        case inputText = "input_text"
        case inputNumber = "input_number"
        case inputOption = "input_option"
        // No such case here for the unknowns
    }
}
Run Code Online (Sandbox Code Playgroud)

encodingdecoding部分移至扩展名:

可分解部分:

extension Type: Decodable {
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        // As you already know your RawValues is String actually, you decode String here
        let stringForRawValues = try container.decode(String.self) 
        // This is the trick here...
        switch stringForRawValues { 
        // Now You can switch over this String with cases from RawValues since it is String
        case RawValues.text.rawValue:
            self = .text
        case RawValues.image.rawValue:
            self = .image
        case RawValues.document.rawValue:
            self = .document
        case RawValues.profile.rawValue:
            self = .profile
        case RawValues.sign.rawValue:
            self = .sign
        case RawValues.inputDate.rawValue:
            self = .inputDate
        case RawValues.inputText.rawValue:
            self = .inputText
        case RawValues.inputNumber.rawValue:
            self = .inputNumber
        case RawValues.inputOption.rawValue:
            self = .inputOption

        // Now handle all unknown types. You just pass the String to Type's unknown case. 
        // And this is true for every other unknowns that aren't defined in your RawValues
        default: 
            self = .unknown(stringForRawValues)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

可编码部分:

extension Type: Encodable {
    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        switch self {
        case .text:
            try container.encode(RawValues.text)
        case .image:
            try container.encode(RawValues.image)
        case .document:
            try container.encode(RawValues.document)
        case .profile:
            try container.encode(RawValues.profile)
        case .sign:
            try container.encode(RawValues.sign)
        case .inputDate:
            try container.encode(RawValues.inputDate)
        case .inputText:
            try container.encode(RawValues.inputText)
        case .inputNumber:
            try container.encode(RawValues.inputNumber)
        case .inputOption:
            try container.encode(RawValues.inputOption)

        case .unknown(let string): 
            // You get the actual String here from the associated value and just encode it
            try container.encode(string)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

例子:

我只是将其包装在一个容器结构中(因为我们将使用JSONEncoder / JSONDecoder)为:

struct Root: Codable {
    let type: Type
}
Run Code Online (Sandbox Code Playgroud)

对于未知情况以外的其他值:

let rootObject = Root(type: Type.document)
do {
    let encodedRoot = try JSONEncoder().encode(rootObject)
    do {
        let decodedRoot = try JSONDecoder().decode(Root.self, from: encodedRoot)
        print(decodedRoot.type) // document
    } catch {
        print(error)
    }
} catch {
    print(error)
}
Run Code Online (Sandbox Code Playgroud)

对于大小写未知的值:

let rootObject = Root(type: Type.unknown("new type"))
do {
    let encodedRoot = try JSONEncoder().encode(rootObject)
    do {
        let decodedRoot = try JSONDecoder().decode(Root.self, from: encodedRoot)
        print(decodedRoot.type) // unknown("new type")
    } catch {
        print(error)
    }
} catch {
    print(error)
}
Run Code Online (Sandbox Code Playgroud)

我将示例与本地对象放在一起。您可以尝试使用REST API响应。


小智 6

enum Type: String, Codable, Equatable {
    case image
    case document
    case unknown

    public init(from decoder: Decoder) throws {
        guard let rawValue = try? decoder.singleValueContainer().decode(String.self) else {
            self = .unknown
            return
        }
        self = Type(rawValue: rawValue) ?? .unknown
    }
}
Run Code Online (Sandbox Code Playgroud)


Sco*_*ner 5

这是基于nayem答案的替代方案,它通过使用内部RawValues初始化的可选绑定提供了稍微简化的语法:

enum MyEnum: Codable {

    case a, b, c
    case other(name: String)

    private enum RawValue: String, Codable {

        case a = "a"
        case b = "b"
        case c = "c"
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        let decodedString = try container.decode(String.self)

        if let value = RawValue(rawValue: decodedString) {
            switch value {
            case .a:
                self = .a
            case .b:
                self = .b
            case .c:
                self = .c
            }
        } else {
            self = .other(name: decodedString)
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()

        switch self {
        case .a:
            try container.encode(RawValue.a)
        case .b:
            try container.encode(RawValue.b)
        case .c:
            try container.encode(RawValue.c)
        case .other(let name):
            try container.encode(name)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您确定所有现有的枚举案例名称都与它们代表的基础字符串值匹配,则可以简化RawValue为:

private enum RawValue: String, Codable {

    case a, b, c
}
Run Code Online (Sandbox Code Playgroud)

...并encode(to:)

func encode(to encoder: Encoder) throws {
    var container = encoder.singleValueContainer()

    if let rawValue = RawValue(rawValue: String(describing: self)) {
        try container.encode(rawValue)
    } else if case .other(let name) = self {
        try container.encode(name)
    }
}
Run Code Online (Sandbox Code Playgroud)

这是使用它的一个实际示例,例如,您想对SomeValue具有要建模为枚举的属性进行建模:

struct SomeValue: Codable {

    enum MyEnum: Codable {

        case a, b, c
        case other(name: String)

        private enum RawValue: String, Codable {

            case a = "a"
            case b = "b"
            case c = "letter_c"
        }

        init(from decoder: Decoder) throws {
            let container = try decoder.singleValueContainer()
            let decodedString = try container.decode(String.self)

            if let value = RawValue(rawValue: decodedString) {
                switch value {
                case .a:
                    self = .a
                case .b:
                    self = .b
                case .c:
                    self = .c
                }
            } else {
                self = .other(name: decodedString)
            }
        }

        func encode(to encoder: Encoder) throws {
            var container = encoder.singleValueContainer()

            switch self {
            case .a:
                try container.encode(RawValue.a)
            case .b:
                try container.encode(RawValue.b)
            case .c:
                try container.encode(RawValue.c)
            case .other(let name):
                try container.encode(name)
            }
        }
    }

}

let jsonData = """
[
    { "value": "a" },
    { "value": "letter_c" },
    { "value": "c" },
    { "value": "Other value" }
]
""".data(using: .utf8)!

let decoder = JSONDecoder()

if let values = try? decoder.decode([SomeValue].self, from: jsonData) {
    values.forEach { print($0.value) }

    let encoder = JSONEncoder()

    if let encodedJson = try? encoder.encode(values) {
        print(String(data: encodedJson, encoding: .utf8)!)
    }
}


/* Prints:
 a
 c
 other(name: "c")
 other(name: "Other value")
 [{"value":"a"},{"value":"letter_c"},{"value":"c"},{"value":"Other value"}]
 */
Run Code Online (Sandbox Code Playgroud)


jac*_*ckx 5

让我们从一个测试用例开始。我们预计这会通过:

    func testCodableEnumWithUnknown() throws {
        enum Fruit: String, Decodable, CodableEnumWithUnknown {
            case banana
            case apple

            case unknown
        }
        struct Container: Decodable {
            let fruit: Fruit
        }
        let data = #"{"fruit": "orange"}"#.data(using: .utf8)!
        let val = try JSONDecoder().decode(Container.self, from: data)
        XCTAssert(val.fruit == .unknown)
    }
Run Code Online (Sandbox Code Playgroud)

我们的协议CodableEnumWithUnknown表示支持unknown解码器在数据中出现未知值时应使用的情况。

然后是解决方案:

public protocol CodableEnumWithUnknown: Codable, RawRepresentable {
    static var unknown: Self { get }
}

public extension CodableEnumWithUnknown where Self: RawRepresentable, Self.RawValue == String {

    init(from decoder: Decoder) throws {
        self = (try? Self(rawValue: decoder.singleValueContainer().decode(RawValue.self))) ?? Self.unknown
    }
}
Run Code Online (Sandbox Code Playgroud)

诀窍是让你的枚举实现CodableEnumWithUnknown协议并添加unknown大小写。

我喜欢上面使用其他帖子中提到的实现的解决方案.allCases.last!,因为我发现它们有点脆弱,因为编译器没有对它们进行类型检查。