What does "\.self" actually do in swift/swiftUI?

Viewed 2806

I don't fully understand what exactly \.self does in the following code:

struct ContentView: View {
    @State private var numbers = [Int]()
    @State private var currentNumber = 1

    var body: some View {
        VStack {
            List {
                ForEach(numbers, id: \.self) {
                    Text("\($0)")
                }
            }

            Button("Add Number") {
                self.numbers.append(self.currentNumber)
                self.currentNumber += 1
            }
        }
    }
}

I'm following this: https://www.hackingwithswift.com/books/ios-swiftui/deleting-items-using-ondelete.

I have a really basic understanding of the language right now, so I may not understand high level explanations, so would prefer very simple explanations or analogies with verbose descriptions. I think it is setting the idfor each list item as each item in the numbers array? Correct me if wrong - but is each id being set as whatever Int is in each entry of the numbers array? If so, then what does \ actually do when typing \.self and what does .self actually do in combination with \?

2 Answers

id: .self tells Swift to use as unique id (keypath) the hash of the object. It explains why the name "self" is used. id: .self is especially useful for the basic Swift types like Integer and String. On the one the hand the developer cannot add to them an unique id. On the other hand all they are hashable so we can use id: .self. id: .self is useful not only for ForEach, but for List also.

Related