Search code examples
swiftspecial-charactersswiftui

What is the backslash(\) used for in SwiftUI?


In the Apple tutorial for SwiftUI called "Composing Complex Interfaces", the tutorial uses a backslash that doesn't appear to be string interpolation or an escape character. This is the line:

ForEach(categories.keys.sorted().identified(by: \.self))

What is the purpose of this backslash?

Below is the entire Struct that contains it.

struct CategoryHome: View {
    var categories: [String: [Landmark]] {
        .init(
            grouping: landmarkData,
            by: { $0.category.rawValue }
        )
    }

    var body: some View {
        NavigationView {
            List {
                ForEach(categories.keys.sorted().identified(by: \.self)) { key in
                    Text(key)
                }
            }
            .navigationBarTitle(Text("Featured"))
        }
    }
}

Solution

  • \.self it's a identity keypath that apple added for:

    Add the ability to reference the identity key path, which refers to the entire input value it is applied to.

    More info in proposal.