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

Anton Zhilin antonyzhilin at gmail.com
Mon Jun 27 12:33:26 CDT 2016


> 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(.getBar)

This can be done now:
let bars = foos.map(Foo.getBar)

> While for parameterless functions this might not seem like much of an
> improvement, I think it helps when there are parameters involved:
> 
> struct Foo {
>     let bar: Int
> 
>     func combine(other: Foo) -> Foo {
>         return Foo(bar: other.bar + self.bar)
>     }
> }
> 
> let foos = [Foo(bar: 5), Foo(bar: 6), Foo(bar: 1)]
> let reduced = foos.reduce(Foo(bar: 0), .combine)

This also can be done now:
let reduced = foos.reduce(Foo(bar: 0), Foo.combine)

Are you suggesting to drop class name? That might make sense, but not 
for Swift 3.



More information about the swift-evolution mailing list