[swift-evolution] [Pitch] KeyPath based map, flatMap, filter

Hooman Mehr hooman at mac.com
Sat Jul 8 15:10:36 CDT 2017


I like this promote operator idea. I have been defining similar operators for specific projects almost at random. It makes sense to come up with a well-defined behavior and name for such operators, as a common practice as you suggest.

The problem with the postfix operator is that it does not currently work without an extra set of parenthesis:

postfix operator ^

postfix func ^<T,U>(lhs: KeyPath<T,U>) -> (T)->U { return { $0[keyPath: lhs] } }

struct Guy { let name: String }

let guys = [
    Guy(name: "Benjamin"),
    Guy(name: "Dave"),
    Guy(name: "Brent"),
    Guy(name: "Max")
]

guys.map(\.name^) // Error: Invalid component of Swift key path

guys.map((\.name)^) // This works

Is this a bug? 

That is the reason I used a prefix operator (~) in my suggestion in the a previous e-mail on this thread.


> On Jul 7, 2017, at 4:27 PM, Dave Abrahams via swift-evolution <swift-evolution at swift.org> wrote:
> 
> By the way, if you're worried about whether subtyping will fly, I've
> recently been thinking there might be a role for a “promotion” operator
> that enables lossless “almost-implicit” conversions, e.g.:
> 
>    someNumber^      is equivalent to    numericCast(someNumber)
>    \.someKeyPath^   is equivalent to    { $0\.someKeyPath }
>    someSubstring^   is equivalent to    String(someSubstring)
> 
>    etc.
> 
> This convenience can be implemented by anyone today for keypaths, and
> will provide nearly the syntax you're looking for.  This is exactly the
> sort of thing I'd love to see become a widespread existing practice
> before we incorporate it in the standard library, so we could properly
> judge its impact on real code.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170708/e58952a0/attachment.html>


More information about the swift-evolution mailing list