I have the following simple lines of code.
import SwiftUI
struct ContentView: View {
var users = ["Susan", "Kate", "Natalie", "Kimberly", "Taylor", "Sarah", "Nancy", "Katherine", "Nicole", "Linda", "Jane", "Mary", "Olivia", "Barbara"]
var body: some View {
List {
ForEach(users, id: \.self) { user in
Text(user)
}
}
}
}
So I'm just listing names. What I want to ask is what is id and what .self means. If I look up the doc under ForEach, it says the following.
Either the collection’s elements must conform to Identifiable or you need to provide an id parameter to the ForEachinitializer.
Does the compiler automatically generate a unique string like UUID for each element in the array or something? Can I somehow print the raw value of each id? Muchos thankos.
Does the compiler automatically generate a unique string like UUID for each element in the array or something?
NO. In the code shown, it is the case you need to provide an id parameter to the ForEach
initializer.
Can I somehow print the raw value of each id?
In your case, you specify \.self
for id:
, meaning --
The id
of "Susan"
is "Susan"
itself.
The id
of "Kate"
is "Kate"
itself.
The id
of "Natalie"
is "Natalie"
itself.
...
And so on.
When you define an Identifiable
struct explicitly, for example:
struct User: Identifiable {
var id: String {name}
var name: String
}
Then you have no need to specify id:
in ForEach
:
struct ContentView: View {
var users: [User] = ["Susan", "Kate", "Natalie", "Kimberly", "Taylor", "Sarah", "Nancy", "Katherine", "Nicole", "Linda", "Jane", "Mary", "Olivia", "Barbara"]
.map(User.init(name:))
var body: some View {
List {
ForEach(users) { user in
Text(user.name)
}
}
}
}