Swift - Convert raw value to enumeration

Introduction

Consider the following code:

enum MyColor : String  {
    case Black = "Black"
    case White   = "White"
    case Red  = "Red"
    case Green  = "Green"
    case Yellow  = "Yellow"
}

If you have a string of "Green" , how do you convert it to the enumeration member?

You can do so via the rawValue initializer, as follows:

var myColor2:MyColor? = MyColor (rawValue:"Green")

Because the rawValue initializer does not guarantee that it is able to return an enumeration member, it returns an optional value.

The ? sign is used in the statement.

Once the value is returned, you can proceed to use it:

if myColor2 == MyColor.Green {
    ...
}

To use the rawValue property on myColor2 , you should confirm that it is not nil before proceeding to use it:

//print only if myColor2 is not nil
if myColor2 != nil {
    print(myColor2!.rawValue)
}

You need to have a ! character to force unwrap the value of myColor2 before accessing the rawValue property.

Related Topic