Hey all!
I've been working through Day 16 of 100 Days and got to the lesson about Creating Views in a Loop.
In particular, I was curious about the purpose of the ID parameter and how a view could behave when it's misused. From the tutorial, Paul writes that the "id: \.self
part is important. This exists because SwiftUI needs to be able to identify every view on the screen uniquely, so it can detect when things change"
I tweaked the code provided in the lesson by swapping \.self
with \.count
. My understanding is that this tells SwiftUI to identify the strings with their lengths, rather than the Strings themselves.
struct ContentView: View {
let students = ["Harry", "Hermione", "Ron"]
@State private var selectedStudent = "Harry"
var body: some View {
NavigationView {
Form {
Picker("Select your student", selection: $selectedStudent) {
ForEach(students, id: \.count) {
Text($0)
}
}
}
}
}
}
When running this code, the Picker misbehaves in that it doesn't appear to allow different selections. I'm having trouble wrapping my mind around why this is the case.
At a glance, the count
values for the strings provided above should all be unique (5, 8, and 3 respectively). Skimming the documentation about forEach for lists, my understanding is that ID just needs to be hashable. Since the .count
property of strings is an Integer, and integers are hashable, would't this criteria be met? What else could explain why the views are not created or behaving as intended?
Apologies ahead of time if my question is framed poorly. I'm not too familiar with the underlying behavior of SwiftUI views, so wondering if someone more experienced could shed light on what could be going on here.
TL;DR Why does the picker misbehave if we choose to use \.count
as the identifier above, rather than \self
or another string property like \.debugDescription
?
Any pointers or suggestions for how to further investigate this would be greatly appreciated. Thank you!