Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swift initialize array of repeated values with variable IDs

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

you could try this approach, works for me:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading