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

Using Enums with raw values

We saw how easy it is to create enums with raw values. Now, let's take a look at how to get the raw value of enums or create enums back using raw values.

We already saw how to get the raw value from enum by just calling .rawValue to return the raw value of the enum case.

To initialize an enum with a raw value, the enum should be declared with a type; so in that case, the enum will have a default initializer to initialize it with a raw value. An example of an initializer will be like this:

let httpCode = HTTPCode(rawValue: 404)  // NotFound 
let httpCode2 = HTTPCode(rawValue: 1000) // nil 

The rawValue initializer always returns an optional value because there will not be any matching enum for all possible values given in rawValue. For example, in case of 404, we already have an enum whose value is 404. However, for 1000, there is no enum with such value, and the initializer will return nil in that case. So, before using any enum initialized by the rawValue initializer, you have to check first whether the value is not equal to nil; the best way to check for enums after initialization is by this method:

if let httpCode = HTTPCode(rawValue: 404){ 
   print(httpCode) 
} 
if let httpCode2 = HTTPCode(rawValue: 1000){ 
   print(httpCode2) 
} 

The condition will be true only if the initializer succeeds to find an enum with the given rawValue.

主站蜘蛛池模板: 巧家县| 万全县| 桦甸市| 峨山| 公安县| 博兴县| 汉川市| 从江县| 自贡市| 社旗县| 红安县| 吕梁市| 承德县| 洛隆县| 特克斯县| 扶余县| 安国市| 神木县| 辰溪县| 鸡东县| 许昌市| 襄垣县| 商城县| 巩留县| 武城县| 深州市| 邹城市| 玛纳斯县| 鄄城县| 安顺市| 阿拉善盟| 威信县| 禄丰县| 清苑县| 房产| 娱乐| 绥中县| 宣威市| 平陆县| 手机| 海淀区|