iOS - 如何使用未知类型声明Swift枚举属性?

时间:2018-06-05 01:52:59

标签: ios swift enums

我正在尝试创建一个Swift枚举,它会声明Type的属性,以便我可以在Enum.type调用中调用JSONDecoder().decode。我想知道以下内容:

  1. 这在Swift中甚至可能吗?
  2. 语法是什么样的?
  3. 我已经给了它以下尝试:

    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)
    

    完全有可能我只是想在这里过于聪明,并且有一个更简单的解决方案。

1 个答案:

答案 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)
}
相关问题