官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 岳阳市| 阿合奇县| 忻州市| 界首市| 宁南县| 云林县| 文安县| 兴城市| 徐州市| 宁远县| 新丰县| 清丰县| 石首市| 嘉善县| 克什克腾旗| 商城县| 运城市| 都江堰市| 会昌县| 集贤县| 会泽县| 乐安县| 泗洪县| 奉新县| 甘谷县| 金华市| 双辽市| 永靖县| 来宾市| 沂水县| 夏津县| 德阳市| 武夷山市| 上高县| 安顺市| 灵丘县| 河南省| 武汉市| 大姚县| 同德县| 阿拉善右旗|