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

How it works...

When used in C and Objective-C, enums are defined as a type definition on top of an integer, with each case being given a defined integer value. In Swift, enums do not need to represent integers under the hood; in fact, they do not need to be backed by any type, and can exist as their own abstract concepts. Consider the following example:

enum CompassPoint { 
case North, South, East, West
}
Note that we can define multiple cases on the same line by separating them with commas.

For Title, an integer-based enum doesn't seem appropriate; however, a string-based one may be. So, let's declare our enum to be string based:

enum Title: String { 
case mr = "Mr"
case mrs = "Mrs"
case mister = "Master"
case miss = "Miss"
case dr = "Dr"
case prof = "Prof"
case other // Inferred as "other"
}

The enum's raw type is declared after its name and a : separator. The raw types that can be used to back the enum are limited to types that can be represented as a literal; this includes Swift base types--String, Int, Float, and Bool.

These types can be used to back an enum because they conform to a protocol, called RawRepresentable. We will cover protocols later in the chapter.

Cases can be assigned a value of the raw type; however, certain types can be inferred, and so do not need to be explicitly declared. For Int-backed enums, the inferred values are sequentially assigned starting at 0:

enum Rating: Int { 
case worst // Infered as 0
case bad // Infered as 1
case average // Infered as 2
case good // Infered as 3
case best // Infered as 4
}

For string-based enums, the inferred value is the name of the case, so the other case in our Title enum is inferred to be other.

We can get the underlying value of the enum in its raw type by accessing its rawValue property:

let title1 = Title.mr 
print(title1.rawValue) // "Mr"
主站蜘蛛池模板: 海南省| 通渭县| 准格尔旗| 蒙山县| 福鼎市| 馆陶县| 南丹县| 小金县| 梅河口市| 柏乡县| 富阳市| 敦化市| 溧阳市| 峨眉山市| 涟源市| 进贤县| 肇州县| 黑龙江省| 钟祥市| 镇坪县| 西峡县| 平舆县| 和顺县| 南华县| 葵青区| 浏阳市| 资溪县| 绍兴县| 黔西县| 浮梁县| 正镶白旗| 棋牌| 讷河市| 铁岭县| 右玉县| 屏东县| 阿拉尔市| 肥乡县| 湟中县| 盐亭县| 广汉市|