Is there somewhere to read up on exactly how leading dot inference works?

I'm not sure if "leading dot inference" is the right term, but what I'm talking about is how the swift compiler can infer the type in some cases, and you can just type a . prefix to a static member.

For instance if I have an enum, I can type this:

let x = MyEnum.someCase

Or in some cases, I can use this shorthand:

let x = .someCase

Is there any documentation on exactly what circumstances this form of inference can be used, and what the boundary conditions are?

I am also interested in how the compiler knows which type should be inferred here.

I don't know if there's a great comprehensive reference for this syntax but the basic idea is that if there's a situation where the compiler knows what the type of an expression 'should' be (i.e., it can deduce the type via inference) then you can access static members on that type without writing the type name explicitly. I think the first (and possibly only?) mention of this syntax in TSPL is in the Enumerations section:

The type of directionToHead is inferred when it’s initialized with one of the possible values of CompassPoint . Once directionToHead is declared as a CompassPoint , you can set it to a different CompassPoint value using a shorter dot syntax:

directionToHead = .east

The type of directionToHead is already known, and so you can drop the type when setting its value. This makes for highly readable code when working with explicitly typed enumeration values.

Note that the example you've written above:

Will not in general compile because the compiler has no information about what the type of the expression 'should' be. OTOH, if you write:

let x: MyEnum = .someOtherCase

or

var x = MyEnum.someCase
x = .someOtherCase

then the compiler knows that the expression on the right hand side of the = 'should' have type MyEnum, so it can figure out that you're referring to MyEnum.someOtherCase.

Also note that there are recent and ongoing developments in this area to increase the number of cases where the compiler is able to infer the base type, and ongoing bug fixes to improve type inference may open up additional possibilities as well!

3 Likes

Just an additional to what Frederick mentioned, although there isn't a guide in specific for leading dot base inference, there is this great talk Embrace Swift type inference - WWDC 2020 - Videos - Apple Developer on type inference by @hborla in the WWDC that may give you an general understanding on the inference in the compiler :)

2 Likes
Terms of Service

Privacy Policy

Cookie Policy