SE-0249: Key Path Expressions as Functions

Source compatibility tests against the implementation as modified in #23435 looked good. Compiler performance showed a 0.05%–0.5% regression, which is small enough that it could easily be noise.

7 Likes

A big +1 for this proposal. It is a very targeted and elegant solution.

I hope to see the @callable direction flushed out in the future...

What is your evaluation of the proposal?

A very strong +1.

Is the problem being addressed significant enough to warrant a change to Swift?

Yes. It just feels natural. I've been writing array.map(\.property) many times, which was followed by a recurring dissapointing realization that this is not implemented yet.

Does this proposal fit well with the feel and direction of Swift?

Definitely.

How much effort did you put into your review? A glance, a quick reading, or an in-depth study?

Read the proposal.

I support this proposal, but I'd like to see the following details clarified:

Resolve priority
The proposal doesn't mention overloading.

With the PR, the following is ambiguous:

class C {
    var foo: Int = 0
}

func take(_ arg: KeyPath<C, Int>) {}
func take(_ arg: (C) -> Int) {}

take(\C.foo)

I think the explicit KeyPath parameter should be preferred over the implicit conversion. (That would be consistent with explicit C being preferred over AnyObject or AnyHashable.)

Calling of key paths
The proposal doesn't make it clear if key paths can be called directly.

The PR allows the following case:

let _ = (\C.foo)(C())

I think there is no benefit to this and it's confusing, so I propose we don't allow it (at least until a general @callable is considered).

A disambiguation rule was added in the rebased version of the PR. (Specifically, the rule is that, when comparing two valid solutions, if one uses a subtype of AnyKeyPath where the other uses a function type, the key path solution's score is incremented so that it will be favored. This can apply to any function-typed value, not just one created with this proposal's syntax.)

4 Likes

Hi everyone,

The review period has now ended and this proposal has been accepted.

Thanks for your feedback during the review!

Ben Cohen
Review Manager

13 Likes

Hello, I would like to ask for the update on this proposal. I see that this proposal has been accepted but not been merged yet. Will it be merged in Swift 5.1?

1 Like

Maybe you just send a ping in the PR, which is here: WIP [ConstraintSystem] Ability to treat key path literal syntax as function type (Root) -> Value. by gregomni · Pull Request #19448 · apple/swift · GitHub