Marcy
Marcy

Reputation: 6009

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"))
        }
    }
}

Upvotes: 23

Views: 4301

Answers (2)

Mehul Thakkar
Mehul Thakkar

Reputation: 12594

In SwiftUI, the backslash operator is used to refer keypath to use inside given block.

from apple:

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

So for example, see this code:

ForEach(["iPhone SE", "iPhone XS Max"].identified(by: \.self)) { deviceName in
        LandmarkList()
            .previewDevice(PreviewDevice(rawValue: deviceName))
}

here while iterating through array, use the self(here - string) as key

Now take another example: where we use array of objects(not string), now in that case the key which is used as key inside block for iterating is id.

List(landmarkData.identified(by: \.id)) { landmark in
        LandmarkRow(landmark: landmark)
}

Upvotes: 18

pacification
pacification

Reputation: 6018

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

Upvotes: 8

Related Questions