Swift - Enumerations with default values

Introduction

Your enumerations can have default values.

All raw values must be of the same type and can be provided for each of the enumeration:

Demo

enum Response  : String { 
    case hello = "Hi" 
    case goodbye = "See you next time" 
    case thankYou = "No worries" 
} 
let hello = Response.hello 
print(hello.rawValue) // "Hi"

Result

You can create an enum from a raw value, but be wary of using this as it can fail:

Response(rawValue: "Hi") // is an optional Response with  .hello inside 

Enumerations with raw values can use implicit values:

Demo

enum Direction  : String { 
    case East, North, West, South 
} 
print(Direction.West.rawValue) // "West"

Result

give an initial value

Demo

enum Element  : Int { 
    case A = 1, B, C, D, E, F, G
} 
print(Element.C.rawValue)/*from   w  w  w . j  a  v  a  2 s . c o  m*/

Result

Related Topic