Home > Net >  Swift difference between list.map(\.property) and list.map { $0.property }
Swift difference between list.map(\.property) and list.map { $0.property }

Time:09-23

I've just noticed that both return the same result but what is this notation:

list.map(\.property)

compared to the usual

list.map { $0.property }

I've noticed that \. is used in many swiftUI example but this code also works outside of any SwiftUI code. I wonder where does this syntax \. come from.

CodePudding user response:

The \ denotes a key path, which can be of one of the key path types. \.property is short for \SomeType.property, where property is a property of SomeType. SomeType is inferred from the context of the map call.

Since SE-0249 was implemented, key path literal expressions can now be used where a function type is expected. The original pitch is also very interesting to read.

occurrences of \Root.value are implicitly converted to key path applications of { $0[keyPath: \Root.value] } wherever (Root) -> Value functions are expected. For example:

users.map(\.email)   

Is equivalent to:

users.map { $0[keyPath: \User.email] }

In your case, assuming property is of type AnotherType, map would have expected a (SomeType) -> AnotherType function as its parameter, but you have used the key path \.property instead. This is the same as passing the closure { $0.property } and also { $0[keyPath: \SomeType.property] }.

You can also pass longer key paths, like \.property1.property2.property3, too. See here for more details on the syntax.

Checking on godbolt.org with some very simple examples, using key paths vs not using them seem to compile to the same assembly when using the -O flag.

  • Related