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

Enumerations

Enumerations are a programming construct that let you define a value type with a finite set of options. Most languages have enumerations (usually abbreviated to enums), including C and, by extension, Objective-C.

An example of an enum from the iOS/macOS SDK is NSComparisonResult, which you would use when sorting items. When comparing for the purposes of sorting, there are only three possible results from a comparison:

  • ascending : The items are ordered in ascending order
  • descending : The items are ordered in descending order
  • same : The items are the same

There are a finite number of possible options for a comparison result; therefore, it's a perfect candidate for being represented by an enum:

enum ComparisonResult : Int { 
case orderedAscending
case orderedSame
case orderedDescending
}

Swift takes the enum concept and elevates it to a first class type. As we will see, this makes enums a very powerful tool for modeling your information.

This recipe will examine how and when to use enums in Swift.

主站蜘蛛池模板: 平昌县| 扬中市| 堆龙德庆县| 宝鸡市| 远安县| 岳西县| 苏尼特右旗| 扶绥县| 湖南省| 舒城县| 红原县| 永昌县| 长子县| 南部县| 大丰市| 泰州市| 微山县| 北京市| 黑龙江省| 邻水| 板桥市| 溧水县| 白玉县| 通渭县| 柳林县| 鞍山市| 保靖县| 肇源县| 万载县| 明溪县| 康平县| 通辽市| 陕西省| 广州市| 舒兰市| 平山县| 玛纳斯县| 隆尧县| 陇南市| 营山县| 张掖市|