我正在尝试创建一个Swift枚举,它会声明Type
的属性,以便我可以在Enum.type
调用中调用JSONDecoder().decode
。我想知道以下内容:
我已经给了它以下尝试:
enum Item {
case property1, property2, property3
var type: Any<T> {
switch self {
case .property1: return ACustomObjectType
case .property2: return AnotherCustomObjectType
case .property3: return AThirdCustomObjectType
}
}
}
现在很明显这不会编译,但是我要调用它的部分看起来像:
JSONDecoder().decode(Item.type, from: data)
完全有可能我只是想在这里过于聪明,并且有一个更简单的解决方案。
答案 0 :(得分:0)
试试这个解决方案
class CustomObject:Decodable {
var id:String
var name: String
var age: String
}
class ACustomObject: CustomObject {
}
class AnotherCustomObject: CustomObject {
}
class AThirdCustomObject:CustomObject {
}
enum Property {
case property1
case property2
case property3
var type:CustomObject.Type {
get {
switch self {
case .property1: return ACustomObject.self
case .property2: return AnotherCustomObject.self
case .property3: return AThirdCustomObject.self
}
}
}
}
let dic = ["id": "122342", "name": "stackoverflow", "age": "22"]
let json = try! JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
do {
let result = try JSONDecoder().decode(Property.property1.type, from: json)
print(result.name)
}catch {
print(error)
}