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

醉酒当歌 提交于 2019-12-01 02:22:53

问题


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

回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/56489766/what-is-the-backslash-used-for-in-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!