[swift-evolution] Change subscripts to use colons

James Froggatt james.froggatt at me.com
Mon Jul 11 15:01:44 CDT 2016


I've written up a draft proposal, suggestions or improvements are welcome, especially relating to the title.



__Change subscript declarations to use a colon__

--Introduction--

Currently, subscript declarations follow the following model:

subscript(externalName internalName: ParamType) -> ElementType {
    get { … }
    set { … }
}

The initial keyword ‘subscript’ is followed by a parameter list, followed by an arrow to the accessed type.


--Motivation--

The arrow, borrowed from function syntax, is very much out of place in this context, and so can act as a mental stumbling block.

Subscripts act like parameterised property accessors. This means, like a property, they can appear on the left hand side of an assignment, and values accessed through subscripts can be mutated in-place. The colon has precedent in declaring this kind of construct, so it makes sense to reuse it here.

--Proposed solution--

A simple replacement of ‘->’ with ‘:’ in the declaration syntax.

--Detailed design--

This would change the above example to look like the following:

subscript(externalName internalName: ParamType) : ElementType {
    get { … }
    set { … }
}


--Impact on existing code--

Existing code would have to update subscripts to use a colon. This can be automated in a conversion to Swift 3 syntax.


--Potential hazards--

Use of colons could have a negative effect on readability. This largely depends on coding style, which can match either of the following:

subscript(_ example: Type) : ElementType

subscript(_ example: Type): ElementType

This issue is most apparent in the latter example, which omits the leading space before the colon, as the colon blends into the closing bracket.

However, the real-world effect of this change is hard to predict, and subscript declarations are rare enough that the consequences of this change are very limited. In addition, the current ‘->‘ syntax can already act as a mental stumbling block.

--Alternatives Considered--

We could leave the syntax as it is, or use an alternative symbol, such as ‘:->’ or ‘<->’.

We could also leave open the possibility of expanding function syntax with ‘inout ->’.


More information about the swift-evolution mailing list