键路径值类型 'Data.Element.ID' 无法转换为上下文类型 'ID'

Key path value type 'Data.Element.ID' cannot be converted to contextual type 'ID'

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

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 { [=12=] }
        self.id = id
    }
}

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

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

extension List where Data.Element: Identifiable, Data.Element.ID == ID {
    init(data: Data) {
        self.data = data.map { [=10=] }
        self.id = \.id
    }
}