iOS Programming Cookbook
上QQ阅读APP看书,第一时间看更新

Assigning raw values

When you assign raw values to enum, you have to define the type in your enum syntax and give value for each case:

enum IntEnum: Int{ 
   case case1 = 50 
   case case2 = 60 
   case case3 = 100 
} 

Swift gives you flexibility while dealing with raw values. You don't have to explicitly assign a raw value for each case in enums if the type of enum is Int or String. For Int type enums, the default value of enum is equal to the value of previous one + 1. In case of the first case, by default it's equal to 0. Let's take a look at this example:

enum Gender: Int{ 
   case Male 
   case Female 
   case Other 
} 
var maleValue = Gender.Male.rawValue  // 0 
var femaleValue = Gender.Female.rawValue // 1 

We didn't set any raw value for any case, so the compiler automatically will set the first one to 0, as it's a no set. For any following case, it's value will be equal to previous case value + 1. Another note is that .rawValue returns the explicit value of the enum case. Let's take a look at another complex example that will make it crystal clear:

enum HTTPCode: Int{ 
   case OK = 200 
   case Created  // 201 
   case Accepted // 202 
    
   case BadRequest = 400 
   case UnAuthorized 
   case PaymentRequired 
   case Forbidden 
    
} 
 
let pageNotFound = HTTPCode.NotFound 
let errorCode = pageNotFound.rawValue  // 404 

We have explicitly set the value of first case to 200; so, the following two cases will be set to 201 and 202, as we didn't set raw values for them. The same will happen for BadRequest case and the following cases. For example, the NotFound case is equal to 404 after incrementing cases.

Now, we see how Swift compiler deals with Int type when you don't give explicit raw values for some cases. In case of String, it's pretty easier. The default value of String enum cases will be the case name itself. Let's take a look at an example:

enum Season: String{ 
   case Winter 
   case Spring 
   case Summer 
   case Autumn 
} 
 
let winter = Season.Winter 
 
let statement = "My preferred season is " + winter.rawValue // "My preferred season is Winter" 

You can see that we could use the string value of rawValue of seasons to append it to another string.