Search code examples
arraysdictionaryswiftuiduplicates

Why do duplicate elements in a SwiftUI array cause a warning?


For a word game, I am using .map to create an array of the letters of a guessed word, for example:

var guessWordArray = "BALANCE".map{String($0)}

which creates the array

["B", "A", "L", "A", "N", "C", "E"]

but then I get the warning,

"...the ID A occurs multiple times within the collection, this will give undefined results."

I don't understand why an array with duplicate elements would "give undefined results." Is this an improper use of an array? Is there an alternative I should use?

I would expect an array not to 'care' what elements are in it and whether they are all the same, different, or any mix. I am obviously missing something.


Solution

  • The warning message is quite explicit. Looking at the documentation about ForEach, this component needs a unique ID to distinguish the elements that are passed in. In this scenario, you're passing string itself by \.self.

    ["B", "A", "L", "A", "N", "C", "E"]

    You can see "A" character appears twice within the array, that's why the warning occurs.


    As @workingdog mentioned above, you need to create a model that fully conforms to Identifiable, something like:

    struct CharacterElement: Identifiable {
        var id = UUID()
        var value: String
    }
    

    After that, you're able to remove \.self within ForEach:

    var words = "BALANCE".map { CharacterElement(value: String($0)) }
    
    var body: some View {
        ForEach(words) {
            //TODO:
        }
    }