Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use reserved keyword a enum case

Tags:

enums

swift

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

For example:

enum MyEnum {
  case Self // compiler complains 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?

like image 868
Gabriele Petronella Avatar asked Jul 09 '15 10:07

Gabriele Petronella


1 Answers

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`
  case AnotherCase
}

and use it with or without backticks

let x: MyEnum = .Self
let y = MyEnum.`Self`
like image 129
vadian Avatar answered Nov 01 '22 10:11

vadian