3

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!

2 Answers 2

2

I prefer this approach

var myVariable = (1...3).map { _ in CustomStruct(value: " ") }
Sign up to request clarification or add additional context in comments.

Comments

1

you could try this approach, works for me:

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

1 Comment

There is no reason to use an Array for this. AnyIterator { }.prefix(3)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.