Search code examples
swiftuiswiftui-foreach

What does "\.self" actually do in Swift/SwiftUI?


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 \?


Solution

  • . key paths. ForEach needs every object unique. give them unique ids with id:.self. if your objects are identifiable you dont need .self. i wrote about this in medim if you want you can check out