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"))
}
}
}
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.
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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With