A question about Swift enum syntax

I would have thought the following code would not compile. Spoiler: It compiles, at least in Xcode 14.3.

Does this mean using a dot before an enum case name is just for show?

enum Stuff {
    case first
    case second
    case third

    static var allCases: [Stuff] {
        [.first, .second, third]
    }
}
Answered by Scott in 765619022

Does this mean using a dot before an enum case name is just for show?

Not quite. This compiles because allCases is declared in the same scope as the cases, so it knows what third is by simple name resolution. You could even declare allCases like this:

static let allCases = [first, second, third]

But if you were to use the cases outside the enum body, then the dot is needed to make them into implicit member expressions with type inference:

let allStuffCases: [Stuff] = [.first, .second, .third]

Or here’s another way to let type inference do its thing:

let allStuffCases = [Stuff.first, .second, .third]

Does this mean using a dot before an enum case name is just for show?

You missed it, it is needed.

This will not compile, with error "Extraneous '.' in enum 'case' declaration"

    enum Stuff {
        case .first
        case .second
        case .third

        static var allCases: [Stuff] {
            [.first, .second, third]
        }
    }

You need dot when you refer to a case.

.first stands for Stuff.first, as you do in allCases.

Accepted Answer

Does this mean using a dot before an enum case name is just for show?

Not quite. This compiles because allCases is declared in the same scope as the cases, so it knows what third is by simple name resolution. You could even declare allCases like this:

static let allCases = [first, second, third]

But if you were to use the cases outside the enum body, then the dot is needed to make them into implicit member expressions with type inference:

let allStuffCases: [Stuff] = [.first, .second, .third]

Or here’s another way to let type inference do its thing:

let allStuffCases = [Stuff.first, .second, .third]
A question about Swift enum syntax
 
 
Q