Enum with same named cases

Should this compile (it currently does):

enum SimpleMaterialPreset {
    case metal
    case plastic(grayLevel: Float)
    case plastic(red: Float, green: Float, blue: Float)
}

let p1 = SimpleMaterialPreset.metal
print(p1)

let p2 = SimpleMaterialPreset.plastic(grayLevel: 0.25)
print(p2)

let p3 = SimpleMaterialPreset.plastic(red: 0.5, green: 0.75, blue: 1.0)
print(p3)

// Will print:
// metal
// plastic(grayLevel: 0.25)
// plastic(red: 0.5, green: 0.75, blue: 1.0)

?

Note that two cases share the same name (but they have different associated types).

It will lead to weirdness when switching over it (try conforming SimpleMaterialPreset to CustomStringConvertible for example and you'll see what I mean).


Some examples of what currently is and isn't allowed.

All examples without an error-comment compiles:

enum E {
    case a
    case a // ERROR: Invalid redeclaration of 'a'
    case b
}

enum E {
    case a(Int)
    case a(Bool) // ERROR: Invalid redeclaration of 'a'
    case b
}

enum E {
    case a(Int)
    case a(foo: Int)
    case b
}
print(E.a(123))      // Prints a(123)
print(E.a(foo: 123)) // Prints a(foo: 123)
print(E.b)           // Prints b
2 Likes

This is part of SE-0155. However, it looks like this has not been fully implemented yet.

2 Likes

CC @codafi, sorry I pinged you again, but could you update us on the current status of your implementation? Are there any implementation blockers? Any chance we'll see this proposal finally implemented in Swift 5? Your hard work is much appreciated.

2 Likes
Terms of Service

Privacy Policy

Cookie Policy