[swift-evolution] [Idea] Syntactic sugar for using methods as functions
Manuel Krebber
admin at wheerd.de
Mon Jun 27 05:00:54 CDT 2016
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 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)) { $0.combine(other: $1) }
Which could become:
let reduced = foos.reduce(Foo(bar: 0), .combine)
This would also enable easier usage of custom operators for partial
functions etc. on these methods.
Basically whenever there is a parameter type (T, ...) -> U somewhere,
one could write the prefix dot shortcut and the compiler would look for
a method in type T with a signature (...) -> U and wrap the call to the
method in a closure. In case that no such method can be found or it
cannot be uniquely determined, it will result in a compile time error.
This is just an idea though. Do you think this would be useful? I could
see it help libraries like the Dollar library. It could then be used in
both functional and object oriented ways, since most functions could
become methods while maintaining a short syntax.
Kind regards, Manuel
More information about the swift-evolution
mailing list