Swift 4中带有默认大小写的可枚举枚举 [英] Codable enum with default case in Swift 4
问题描述
我已经定义了枚举
如下:
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
}
映射JSON字符串属性。
自动序列化和反序列化工作正常,但是我发现如果遇到不同的字符串,反序列化将失败。
that maps a JSON string property. The automatic serialization and deserialization works fine, but I found that if a different string is encountered, the deserialization fails.
是否可以定义一个未知
的情况来映射其他可用情况?
Is it possible to define an unknown
case that maps any other available case?
这很有用,因为这些数据来自RESTFul API,将来可能会更改。
This can be very useful, since this data comes from a RESTFul API that, maybe, can change in the future.
推荐答案
您可以扩展您的 Codable
类型并在失败的情况下分配默认值:
You can extend your Codable
Type and assign a default value in case of failure:
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
}
}
编辑/更新:
edit/update:
Xcode 11.2•Swift 5.1或更高版本
创建一个默认为 CaseIterable&可解码的
枚举:
protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable
where RawValue: Decodable, AllCases: BidirectionalCollection { }
extension CaseIterableDefaultsLast {
init(from decoder: Decoder) throws {
self = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) ?? Self.allCases.last!
}
}
游乐场测试:
Playground testing:
enum Type: String, CaseIterableDefaultsLast {
case text, image, document, profile, sign, inputDate = "input_date", inputText = "input_text" , inputNumber = "input_number", inputOption = "input_option", unknown
}
let types = try! JSONDecoder().decode([Type].self , from: Data(#"["text","image","sound"]"#.utf8)) // [text, image, unknown]
这篇关于Swift 4中带有默认大小写的可枚举枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!