Logo for tanaschita.com

How to identify objects when using SwiftUI's List and ForEach

Learn to use the \.self key path and the Identifiable protocol in SwiftUI.

14 Oct 2021 · 2 min read

When we use List or ForEach to create dynamic views, SwiftUI needs to know how to identify them. If an object conforms to the Identifiable protocol, SwiftUI will automatically use its id property for identifying.

struct Recipe: Identifiable {
let id = UUID()
let title: String
}
ForEach(recipes) {
RecipeView($0)
}

But what happens if we for example use ForEach on an array of existing types like strings?

Since a String does not conform to the Identifiable protocol, we need to add the id as the second parameter.

let texts = ["a", "b", "c"]
ForEach(texts, id: \.self) {
Text($0)
}

By using \.self, we tell SwiftUI to use the whole object as the identifier. In our case, it tells SwiftUI that each String value in the array is unique and can be used for identifying.

In the last approach, it is important to make sure that the values in the array are unique, since otherwise ForEach might incorrectly reuse the resulting views.

Image of books
Further reading: SwiftUI by Example
For further reading, check out the SwiftUI by Example book by Paul Hudson. It guides you through dozens of common coding problems with hands-on solutions.

Newsletter

Receive a monthly newsletter about the latest articles and tips.

Image of a reading marmot

Related tags

Written by

Articles with related topics

Latest articles and tips