我有一些这样的代码:
var myVariable = Array(repeating: CustomStruct(value: " "), count: 3))
其中CustomStruct
看起来像这样:
struct CustomStruct: Hashable {
var id: UUID = UUID()
var value: String
static func == (lhs: CustomStruct, rhs: CustomStruct) -> Bool {
return lhs.id == rhs.id && lhs.value == rhs.value
}
}
myVariable
的初始化很好,但有一个问题,因为我想要id of every element to be unique,而且,因为我基本上是对同一个项目进行3个克隆,数组中每个元素的ID都不是唯一的.
据我所知,我能解决这个问题的唯一方法是使用暴力,如下所示:
[CustomStruct(value: " "), CustomStruct(value: " "), CustomStruct(value: " ")]
但我不想这样做,因为这个例子已经最小化了,实际上数组中有大约30个单独的元素,所以它将是一个超长的变量声明.
我之所以希望每个元素都是唯一的,是因为我在SwiftUI中使用这个带有ForEach
个循环的数组,并希望执行以下操作:
ForEach(myVariable, id: \.id) {_ in
// do stuff
}
SwiftUI不会抱怨foreach循环中有相同ID的元素.
我意识到一种方法可以是使用一些自定义逻辑通过init()
调用中的数组进行初始化,但我想知道这里是否有其他/更标准的方法.
谢谢