//: Playground - noun: a place where people can play import UIKit //------枚举---------// //1.Swift中的枚举 //描述一个人的性别(0:男,1:女,2:不详) //enum Sex { //枚举类型 // case Male //枚举值 // case Female // case Unknown // //} // ////定义枚举变量 //var mySex : Sex = Sex.Female //mySex = .Male // //var yourSex : Sex = .Unknown // //if yourSex == .Unknown { // // print("此人似男非女") //} // ////2.枚举和switch的结合使用 ///* //为了保证安全性,switch和枚举类型结合使用时: //(1)将所有枚举值列出,所以情况都要考虑 //(2)或者使用default来表示默认情况 //*/ //switch mySex { //case Sex.Male: // print("男生") //case Sex.Female: // print("女生") ////case Sex.Unknown: //// print("不详") //default: // print("无法识别") // //} //3.枚举的原始值 //在Swift中枚举值不是默认为整型,和C,OC中不同。 enum Sex : Int { case Male = 0 case Female = 1 case Unknown = 2 } //打印枚举值的原始值 print(Sex.Unknown.rawValue) //枚举原始值的类型在Swift中做了扩展:String, Character, Int, Float, Double //enum NewSex : String { // case Male = "Male" // case Female = "Female" // case Unknown = "Unknown" // //} //原始值的隐性赋值: //String:默认和枚举值名字相同 //Int:默认从0开始,依次递增1 enum NewSex: String{ case Male, Female, Unknown } print(NewSex.Female.rawValue) //用原始值给变量做初始化 var hisSex = Sex.Male //枚举构造器-->返回是一个可选类型,如果传入的原始值为不合法值,则返回nil var herSex = Sex(rawValue: 5) //可选绑定 if let yourSex = Sex(rawValue: 10) { switch yourSex { case Sex.Male: print("男生") case Sex.Female: print("女生") case Sex.Unknown: print("不详") } } else { print("没有此性别") } //4.枚举的关联值(相关值):存储枚举值一些额外的信息,相关值可以是不同类型的数据 //(1)基本语法 enum Color { case Red(alpha:Float) case Blue(alpha:Float, Y:Float, L:Int) } var myColor:Color = Color.Red(alpha: 0.5) myColor = .Blue(alpha: 1, Y: 100, L: 100) //if myColor == Color.Red(alpha: 0.3) { // // //} switch myColor { case Color.Red(let alpha): print("red alpha = \(alpha)") case Color.Blue(let a, let b, let c): print("Blue a=\(a),b=\(b),c=\(c)") } enum BarCode { case UP }
时间: 2024-10-26 23:15:36