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