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)
}
Sponsorship logo
Preparing for a technical iOS job interview
Check out my new book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, Authentication, Core Data, Concurrency with async/await, Security, Automated Testing and more.
LEARN MORE

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.

Sponsorship logo
Preparing for a technical iOS job interview
Check out my new book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, Authentication, Core Data, Concurrency with async/await, Security, Automated Testing and more.
LEARN MORE

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

swiftui

swift

ios

Understanding basic animations in SwiftUI

Learn different options to animate SwiftUI views.

16 Jan 2023 · 4 min read

Latest articles and tips

© 2023 tanaschita.com

Privacy policy

Impressum