3

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?

1 Answer 1

2

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.

2
  • That is a very interesting hint! I didn't realize that my declaration is in fact an override of Swift's Type declaration.
    – mbi
    Commented Dec 15, 2020 at 18:14
  • 3
    @mbi I go around this naming it Kind
    – Leo Dabus
    Commented Dec 15, 2020 at 18:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.