代码之家  ›  专栏  ›  技术社区  ›  user-44651

动态地将字符串强制转换为JSONDecoder Decodable.Protocol类型

  •  0
  • user-44651  · 技术社区  · 8 年前

    我有一些枚举值,我想强制转换为JSONDecoder可解码的.Protocol类型 decode 方法。

    每个属性枚举对应于 Codable 班级。

    enum Attributes : String {
        case Shapes = "GetShapes"
        case Color  = "GetColors"
        case Size   = "GetSizes"
    }
    

    我想我可以动态地将

    例如

    let results = try? JSONDecoder().decode(GetShapes.self, from: jsonData)
    

    GetShapes.self ,对应于 枚举的值。

    所以我试着用 NSProtocolFromString 但这似乎不管用。

    if let protoRef = NSProtocolFromString(anAttribute.rawValue) {
        if let results = try? JSONDecoder().decode(protoRef, from: jsonData) {
            //Do something
    }
    

    能够将字符串转换为协议将节省我很多工作。


    基本上,取一个字符串“GetShapes”,使用MagicMethod()使其吐出来

    获取形状.self 满足 的参数 JSONDecoder().decode(type: Decodable.Protocol, from: Data)

    func magicMethod(_ string: String) -> Decodable.Protocol {
    
    }
    

    0 回复  |  直到 8 年前