Why is -> in Swift?

Until today, I thought it was clear enough, because we normally look at these kinds of things:

var t: T {
   // get is () -> T
   // set is T -> ()
}

func getT() -> T {
   // return a T
}


That arrow going into T makes visual sense for the getter and function, but not for the setter, so I understand why it's not used for all properties.


However, the arrow would make sense for read-only computed properties:

var computedProperty: T {
   // return a T
}


But why does it even exist to begin with? Why don't functions look like this?

func getT(): T {
   // return a T
}

let getT: (): T = {
  // return a T
}


If it were removed, we'd have a clash with [Input : Output] Dictionary syntax, but that wasn't in the language to begin with, and could be altered to [Input -> Output] and make as much or more sense.

Replies

The colon represents a type declaration for a property, variable, constant, etc., or type inheritance/conformance (which is also a kind of type declaration) for a class, struct or protocol. To me, the arrow represents a mapping which I think is really appropriate and natural for functions (or more generally closures) just as it is used in Swift.

I know that I've absent-mindedly used -> in a computed property declaration and : in a function declaration a few times. It does seem like a bit of an unnecessary distinction.


FWIW, C and its ilk use the same syntax to declare the type of a variable and the return type of a function; each begins with the type and a space, with no special punctuation differentiating one from the other.

Maybe I prefer the arrow notation for functions because I am a physicist. It just seems familiar and consistent with mathematical notation. I think the Swift grammar is better than other languages like C and Java.


If you look at how a closure (in particular) is defined in Swift, it is almost identical to how one would do it in mathematical notation for a map.

That makes sense, if you're coming from that background. A lot of developers are coming from Objective-C, though, and in that background, declaring a getter for a computed property and declaring a method that returns some value are exactly the same. Coming from this background, the dictinction between : and -> can seem inconsistent, and a bit awkward.


I kind of doubt it will change at this stage, though.