【发布时间】:2019-10-09 11:17:38
【问题描述】:
对于给定的 JSON,如下所示:
{
"store": {
"animals": [
{
"type": "dog"
},
{
"type": "cat"
}
]
}
}
我可以使用type 的枚举来解析它,如下所示:
final class AnimalStore: Decodable {
let store: Store
}
extension AnimalStore {
struct Store: Decodable {
let animals: [Animal]
}
}
extension AnimalStore.Store {
struct Animal: Decodable {
let type: AnimalType?
}
}
extension AnimalStore.Store.Animal {
enum AnimalType: String, Decodable {
case dog = "dog"
case cat = "cat"
//case unknown = how such a case could be implemented?
}
}
而且因为它是可选的;如果 json 中缺少 type 键值对,它会正常工作。
但我想有另一种情况,我们称之为unknown,这样如果任何给定的类型不是狗或猫(字符串是别的东西),类型将被初始化为未知。现在,如果给出除了狗或猫以外的类型,它就会崩溃。
除了给定类型之外的其他类型的初始化如何用枚举来实现?
换句话说,对于像"type": "bird" 这样的给定类型,我希望将type 初始化为unknown。
【问题讨论】:
-
我搜索了这样一个问题但找不到,感谢指出重复@LeoDabus
标签: json swift enums decodable