[swift-evolution] [Proposal Idea] dot shorthand for instance members

Radosław Pietruszewski radexpl at gmail.com
Fri Dec 18 13:36:07 CST 2015


Interesting! I’d definitely be for some shortcut syntax here, as this seems to be a very, very common pattern. Passing a function to, say, `map` is so much easier and cleaner than passing a method in Swift — even though Swift generally always prefers methods to functions!

I haven’t spent too much thinking this through, but I think this is sound.

For contexts where a T is expected, .foo means T.foo

But it’s not ambiguous here, because we’re expecting T -> U here, and functions can’t have static members (or any members for that matter :P). So passing a .foo could unambiguously mean T.foo(T) — an instance method on T, returning U.

I’d be for dropping the parens, they seem unnecessary, and are confusing (we’re passing a function, not calling it). It should be unambiguous with properties since methods and properties share a name space.

And, speaking of, I’d also just make it work with properties with the same syntax. So array.map(.foo) would call $0.foo() if `foo` is a method, or $0.foo if `foo` is a property.

(Am I missing something?)

— Radek

> On 18 Dec 2015, at 04:27, Matthew Johnson via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Swift currently offers dot shorthand for static members of type Self in type contexts expecting a value of the type in question.  This is most commonly used with enum cases.
> 
> Swift does not currently offer shorthand for instance members.  Introducing a shorthand for instance members would improve clarity and readability of code in common cases:
> 
> anArray.map{$0.anInstanceMethod()}
> 
> becomes:
> 
> anArray.map(.anInstanceMethod())
> 
> This shorthand would work in typing contexts expecting a single argument function.  It would allow abbreviated access to any visible instance property getter or instance method on the type of the argument.  Of course the return type would need to match the return type expected by the context or a type mismatch compiler error would occur.
> 
> The readability advantage is arguably small but it does exist.  The feature also aligns very well with an existing language feature.
> 
> I think it’s an interesting idea and am wondering whether others feel like it is something worth pursuing or not.
> 
> Matthew
> _______________________________________________
> 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