Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"))
        }
    }
}
like image 385
Marcy Avatar asked Jun 07 '19 07:06

Marcy


People also ask

What is the backslash used for in Swift?

Swift's escape character is \ , the backslash (U+005C). Escape character sequences (shortened to escape sequence) represent special characters. In the current version of Swift, the backslash escape character tells the compiler that a sequence should combine to produce one of these special characters.

How to add backslash in string Swift?

The backslash ( \ ) character is a very special one if it comes to the Swift programming language. We can also use it to write an actual backslash by esaping one ( \\ ), but the newline ( \n ), tab ( \t ) and return ( \r ), characters are also created by using a backslash.


1 Answers

In SwiftUI, the blackslash 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)
}
like image 86
Mehul Thakkar Avatar answered Oct 04 '22 21:10

Mehul Thakkar