user3561494
user3561494

Reputation: 2362

enum in a class in Swift

How do you access a classes enum from outside of the class?

  class Element
  {
    enum Type
    {
        case AUDIO
        case LIGHT
        case THERMOSTAT
    }
  }

  var a = Element.Type.LIGHT   // error: 'Element.Type.Type' does not have a member named 'LIGHT'

  var b = Element.LIGHT   // error: 'Element.Type' does not have a member named 'LIGHT'

Upvotes: 5

Views: 10163

Answers (2)

Ting Yi Shih
Ting Yi Shih

Reputation: 896

It's possible to remain the name Type but you need backticks (`)

class Element {
    enum `Type` {
        case AUDIO
        case LIGHT
        case THERMOSTAT
    }
}

let a: Element.`Type` = .LIGHT

However the following pattern I have tested seems not working:

let a = Element.`Type`.LIGHT // Compile error

Upvotes: 0

Antonio
Antonio

Reputation: 72780

A Type property already exists (unlucky name :)), just rename it to something else, such as:

class Element
{
    enum EnumType
    {
        case AUDIO
        case LIGHT
        case THERMOSTAT
    }
}

var a = Element.EnumType.LIGHT

Upvotes: 11

Related Questions