【问题标题】:Codable - arrayPropety [AnyObject]: Reference to member 'data' cannot be resolved without a contextual typeCodable - arrayPropety [AnyObject]:如果没有上下文类型,则无法解析对成员“数据”的引用
【发布时间】:2019-06-20 11:36:19
【问题描述】:

设置可编码类。 AnyObjects 数组正在创建编译错误:

如果没有上下文类型,则无法解析对成员“数据”的引用

class ClassA<T>: NSObject, Codable {

    // MARK: - Properties

    let title: String
    let data: [T] // data is an array of either Codable objects of ClassB or ClassC. 

    // MARK: - Keyes

    private enum CodingKeys: String, CodingKey {
        case title
        case data
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        title = try container.decode(String.self, forKey: .title)
        data = [T]()
    }

    func encode(to encoder: Encoder) throws {

        var container = encoder.container(
            keyedBy: CodingKeys.self
        )

        try container.encode(title, forKey: .title)
        try container.encode(data, forKey: .data) // Compilation error: Reference to member 'data' cannot be resolved without a contextual type
    }
}

【问题讨论】:

    标签: swift generics codable


    【解决方案1】:

    数据类型T必须符合Encodable/Codable变化

    class ClassA<T:Codable>: NSObject, Codable {
    

    编译器不知道数组泛型元素是否符合Encodable,因此会报错

    【讨论】:

      【解决方案2】:

      encode(_:, forKey:) 方法需要一个符合Encodable 的类型,否则它怎么知道如何编码那个输入参数呢?因此,您要么需要将泛型类型参数更改为要求 Encodable/Codable 一致性,要么不编码 data 变量,如果它不需要成为 JSON 的一部分(因为它似乎不是解码后的 JSON 的一部分)。

      只需使ClassB 和ClassC 也符合Codable,然后更改类型约束将不是问题,您甚至不需要自定义init(from:) 和encode(to:) 方法。

      class ClassA<T: Codable>: Codable {
      
          // MARK: - Properties
          let title: String
          let data: [T] // data is an array of either Codable objects of ClassB or ClassC. 
      }
      

      与您的问题无关,但您不应让 Swift 类继承自 NSObject,除非您需要它来实现 Obj-C 互操作性。与 Obj-C 不同,Swift 类不需要从基类继承。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-01
        • 1970-01-01
        相关资源
        最近更新 更多