有一个具有枚举类型的属性的结构:
struct TestStruct: Decodable {
let id: Int
let name: String
let enumVar: SomeEnum
}
enum SomeEnum: String {
case one = "1099"
case two = "9090"
case three = "878"
}
如何确认可解码协议的枚举以解析TestStruct结构的元素?
我尝试了休闲方式,但是没有用:
extension SomeEnum: Decodable {
enum Key: String, CodingKey {
case one = "1099"
case two = "9090"
case three = "878"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Key.self)
if let one = try container.decodeIfPresent(Swifter.self, forKey: .one) {
self = .one
} else if let two = try container.decodeIfPresent(Swifter.self, forKey: .two) {
self = .two
} else if let twitter = try container.decodeIfPresent(Swifter.self, forKey: .three) {
self = .three
} else {
self = .three
}
}