Codable - arrayPropety [AnyObject]:如果没有上下文类型,则无法解析对成员 'data' 的引用

Codable - arrayPropety [AnyObject]: Reference to member 'data' cannot be resolved without a contextual type

正在设置 Codable Class。 AnyObjects 数组正在创建编译错误:

Reference to member 'data' cannot be resolved without a contextual type

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
    }
}

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

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

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

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

只需让 ClassBClassC 也符合 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 class 继承自 NSObject,除非您需要它来实现 Obj-C 互操作性。 Swift classes 不需要继承基 class 不像 Obj-C.