[swift-evolution] Dot notation as shorthand in subscripts and functions

Haravikk swift-evolution at haravikk.com
Sat Jan 16 03:24:21 CST 2016

So there’s a discussion at the moment about dot notation in switch statements, and it reminds me that I actually would like to see the dot notation expanded beyond switches.

When used in a switch statement the dot notation is a kind of shorthand reference to the type of an enum, but it also seems like for non enums it could be a shorthand reference to self, allowing us to avoid having to write out variable references in a few common cases.

For example, consider the following:

myObject.myArray[myObject.myArray.startIndex] = 0

What I’d love to be able to do is simplify these to the following:

myObject.myArray[.startIndex] = 0

In essence the dot in these cases represents a reference to the object or struct to which the subscript or function belongs, eliminating the need to enter that yet again (or extract into a variable just for neatness).

The only issue I see is if a parameter is an enum, as it could be ambiguous which shorthand is being used, though this is only really an issue if the type has a property with an identical name to an enum case:

enum MyEnum { .One, .Two }
class MyClass {
	var One = “this is a bad idea"
	func myFunction(mode:MyEnum) { /* Do something */ }

var myObject = MyClass()
myObject.myFunction(.One) // Ambiguous, could be myObject.One or MyEnum.One

However, this is a pretty unlikely case since both the type needs to have a property with exactly the same name as one of the enum’s cases, so most of the time the compiler should be able to decide which was meant. It’s even less likely when considering that convention seems to be for enum cases to start with a capital letter, while properties begin with lowercase letters, though there may be an argument that the test for ambiguity should be case insensitive (to protect against typos). However, it’s also possible that when a property and enum case name conflicts that only one will be a valid argument for the subscript/function anyway, so that’s another way that ambiguity can be avoided too.

More information about the swift-evolution mailing list