如何解决在 SwiftUI 中使数组符合可识别性
我有一个关于在 Identifiable
中符合 SwiftUI
的小问题。
在某些情况下,我们需要有一个给定的 MyType 类型以符合 Identifiable
。
但我面临的情况是,我需要使 [MyType](MyType 数组)符合 Identifiable
。
我的 MyType 已经符合 Identifiable
。我应该怎么做才能使 [MyType] 符合 Identifiable
?
解决方法
我建议在结构中嵌入 [MyType]
,然后让结构符合 Identifiable
。像这样:
struct MyType: Identifiable {
let id = UUID()
}
struct Container: Identifiable {
let id = UUID()
var myTypes = [MyType]()
}
用法:
struct ContentView: View {
let containers = [
Container(myTypes: [
MyType(),MyType()
]),Container(myTypes: [
MyType(),MyType(),MyType()
])
]
var body: some View {
/// no need for `id: \.self`
ForEach(containers) { container in
...
}
}
}
,
您可以编写扩展以使 Array
符合 Identifiable
。
由于扩展不能包含存储的属性,而且因为“相同”的两个数组也具有相同的 id
是有意义的,所以您需要计算 id
基于数组的内容。
这里最简单的方法是,如果您可以使您的类型符合 Hashable
:
extension MyType: Hashable {}
这也使得 [MyType]
符合 Hashable
,并且由于 id
可以是任何 Hashable
,您可以使用数组本身作为它自己的 id
:
extension Array: Identifiable where Element: Hashable {
public var id: Self { self }
}
或者,如果您愿意,id
可以是 Int
:
extension Array: Identifiable where Element: Hashable {
public var id: Int { self.hashValue }
}
当然,您可以只为自己的类型 where Element == MyType
执行此操作,但该类型必须为 public
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。