[swift-evolution] [Idea] Syntactic sugar for using methods as functions

Haravikk swift-evolution at haravikk.me
Tue Jun 28 08:35:03 CDT 2016


> On 27 Jun 2016, at 11:00, Manuel Krebber via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Hi everyone,
> 
> I was thinking it would be nice to have a similar short notation for
> using methods in a functional way as there is for enum cases (and as
> I've been told static members in general).
> Let me give a rather contrived example:
> 
> struct Foo {
>    let bar: Int
> 
>    func getBar() -> Int {
>        return self.bar
>    }
> 
> }
> 
> let foos = [Foo(bar: 1), Foo(bar: 2), Foo(bar: 3)]
> let bars = foos.map{ $0.getBar() }
> 
> What I am suggesting is to add syntactic sugar to bridge the gap between
> functional and object oriented programming. So instead you could write
> the following:
> 
> let bars = foos.map(.getBar)

While I see some potential in this, I wonder if it's a bit too ambiguous at the moment, and might require a wider rethink of the dot shorthand; in the example above it's not clear at a glance that this references the .getBar method of elements, vs a property or method of foos, or self, or Self. Enums are kind of a special case, but they are at least a static member so there's a clearer case for them vs this example which is an instance member, which could lead to ambiguity.

I mean, I'd be all for allowing this shorthand for instance members as well, but we'd need to get around issues of this ambiguity, perhaps with a shorthand identifier for type? As pointed out, you can actually use Foo.getBar, but while this is fine for a type with such a short name, it's not convenient if your type name is much longer, meaning in many cases it will remain easiest to just do { $0.getBar() } or similar. If we could reserve a special type identifier, or use $T or something it might be easier, but it'd need to be an elegant choice (I don't really like either of mine, it's just to give the idea).


More information about the swift-evolution mailing list