Home > Mobile >  Swift initialize array of repeated values with variable IDs
Swift initialize array of repeated values with variable IDs

Time:07-25

I have some code like this:

var myVariable = Array(repeating: CustomStruct(value: " "), count: 3))

where CustomStruct looks like this:

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
    }
}

The initialization of myVariable works fine, but there is a problem because I want the id of every element to be unique, and, because I am essentially making 3 clones of the same item, the ids of every element in the array won't be unique.

As far as I can tell, the only way I can solve this problem is to do brute force it, like this:

[CustomStruct(value: " "), CustomStruct(value: " "), CustomStruct(value: " ")]

but I'd rather not do that, because this example has been minimized and in reality I have ~30 individual elements in the array, so it would be a super long variable declaration.

The reason I want every element to be unique is because I'm using this array with a ForEach loop in SwiftUI, and want to do something like this:

ForEach(myVariable, id: \.id) {_ in
   // do stuff
}

without SwiftUI complaining that there are elements with the same ID in the foreach loop.

I realize one approach could be to initialize through the array in the init() call with some custom logic but I was wondering if there is an alternative/more standard approach here.

Thanks!

CodePudding user response:

you could try this approach, works for me:

var myVariable = Array(repeating: (), count: 3).map { CustomStruct(value: " ") }
  • Related