Gabriele Petronella
Gabriele Petronella

Reputation: 108159

Use reserved keyword a enum case

Is it possible to use a reserved keyword as enum case?

For example:

enum MyEnum {
  case self // compiler will complain here
  case anotherCase
}

In other languages this is possible by escaping the keyword in some ways, for instance in scala we use backticks, e.g.

`type`

can be used as identifier, despite type being a reserved keyword.

Is there anything similar in swift?

Upvotes: 28

Views: 7371

Answers (1)

vadian
vadian

Reputation: 285200

From the Swift Language Guide (Naming Constants & Variables section)

If you need to give a constant or variable the same name as a reserved Swift keyword, surround the keyword with back ticks (`) when using it as a name. However, avoid using keywords as names unless you have absolutely no choice.

enum MyEnum {
  case `self` // compiler does not complain anymore
  case anotherCase
}

and use it with or without backticks

let x: MyEnum = .self
let y = MyEnum.`self`

Upvotes: 44

Related Questions