首页 Referencing initializer 'init(_:id:content:)' on 'ForEach' requires that 'xxxxxx' conform to 'Hashable'
文章
取消

Referencing initializer 'init(_:id:content:)' on 'ForEach' requires that 'xxxxxx' conform to 'Hashable'

iOS13 苹果推出了 SwiftUI, 迫不及待的安装了 Xcode 11 来尝尝鲜.

照着官方教程一步一步敲代码, 还是报了这个错误: Referencing initializer 'init(_:id:content:)' on 'ForEach' requires that 'xxxxxx' conform to 'Hashable'.

之所以报这个错误是因为: ForEachSwiftUI 中一个用来遍历元素, 并生成对应 View collection 的类型. ForEach 的参数为一个 数组, 但是数组内的元素必须要满足 Identifiable 协议. 要解决这个问题可以通过某个支持 Hashablekeypath 获取一个等效的元素为 Identifiable 的数组 .此处最简单的解决方法就是:

加入这段代码:

1
extension xxxxxx: Hashable {}

然后编译顺利通过.

本文由作者按照 CC BY 4.0 进行授权