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

Charlie Monroe charlie at charliemonroe.net
Mon Jun 27 13:27:28 CDT 2016


> On Jun 27, 2016, at 7:33 PM, Anton Zhilin via swift-evolution <swift-evolution at swift.org> wrote:
> 
>> 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)

This will only get you an array of closures:

let bars = foos.map(Foo.getBar) // [() -> Int, () -> Int, () -> Int]
bars[0] // () -> Int
bars[0]() // 1


> 
>> 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.
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution



More information about the swift-evolution mailing list