0

我有一个关于符合Identifiablein的小问题SwiftUI

在某些情况下,我们需要有一个给定的类型 MyType 才能符合Identifiable

但我面临的情况是,我需要有 [MyType](MyType 的数组)才能符合Identifiable.

我的 MyType 已经符合Identifiable. 我应该怎么做才能使 [MyType] 符合Identifiable

4

2 回答 2

2

我建议嵌入[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
            ...
        }
    }
}
于 2021-06-21T02:33:32.113 回答
0

您可以编写扩展以符合Arrayto Identifiable

由于扩展不能包含存储的属性,而且因为“相同”的两个数组也具有相同的 是有意义的,因此id您需要id根据数组的内容计算 。

这里最简单的方法是如果您可以使您的类型符合Hashable

extension MyType: Hashable {}

这也使得[MyType]符合Hashable,并且因为id可以是 any 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 }
}

当然,您可以只为自己的 type 执行此操作where Element == MyType,但该 type 必须是public.

于 2021-06-21T12:56:53.780 回答