Search code examples
swiftenumsreserved-words

How to declare and init nested enum with reserved keyword as type name in Swift?


I'm having a hard time to figure out how to declare a certain nested enum and calling one of it's automatic constructors. This enum i'm trying to declare is supposed to have a reserved keyword as type name.

Here is a simplified example of what i'm trying to do:

import Foundation

public class Foo {}

public extension Foo {
    enum `Type`: Int {
        case bar
    }
}

var type: Foo.`Type`
type = Foo.`Type`(rawValue: 0)

This doesn't compile in Swift 5.2 with error

error: type 'Foo.Type' has no member 'init'

I'm pretty sure it is just a matter of getting the syntax right but i just can't figure it out. Anyone can please explain how to do it or is it just impossible all together?


Solution

  • There is no way to do this specific thing you want to do. That's why nobody uses nested types named Type, even though we all want to—the language already provides this type, and you don't get to override it with your own. We all use the Objective-C style naming of just smashing the word Type right up there without a proper delimiter.

    FooType is what you've got to work with.