1

Key path value type 'Data.Element.ID' cannot be converted to contextual type 'ID'当传递的数据包含已经从 Identifiable 继承的元素时,尝试在下面的扩展中创建初始化程序时出现错误。

struct List<Data, ID> where Data: RandomAccessCollection, ID: Hashable {
    private let data: [Data.Element]
    private let id: KeyPath<Data.Element, ID>

    init(data: Data, id: KeyPath<Data.Element, ID>) {
        self.data = data.map { $0 }
        self.id = id
    }
}

extension List where Data.Element: Identifiable {
    init(data: Data) {
        self.data = data.map { $0 }
        self.id = \Data.Element.id // Compilation Error: Key path value type 'Data.Element.ID' cannot be converted to contextual type 'ID'
    }
}
4

1 回答 1

2

Data.Element.ID不保证是 type List.ID。您可以通过添加另一个类型类型约束来解决此问题。

extension List where Data.Element: Identifiable, Data.Element.ID == ID {
    init(data: Data) {
        self.data = data.map { $0 }
        self.id = \.id
    }
}
于 2020-04-16T10:39:49.973 回答