//穷举匹配 directionToHead = .south switch directionToHead { case .north: print("Lots of planets have a north") case .south: print("Watch out for penguins") case .east: print("Where the sun rises") case .west: print("Where the skies are blue") } // 打印 "Watch out for penguins”
// 使用default分支匹配 let somePlanet =Planet.earth switch somePlanet { case .earth: print("Mostly harmless") default: print("Not a safe place for humans") } // 打印 "Mostly harmless”
与Objective-C不同
Swift 的枚举成员在被创建时不会被赋予一个默认的整型值。在上面的CompassPoint例子中,north,south,east和west不会被隐式地赋值为0,1,2和3。相反,这些枚举成员本身就是完备的值,这些值的类型是已经明确定义好的CompassPoint类型。
//指定原始值类型 enumTextAlignment: Int{ case left //原始值为0 case right //原始值为1 case center //原始值为2 }
指定原始值
使用rawValue获取成员变量的原始值;
每个带原始值的枚举类型都可以用rawValue参数创建,并返回可空枚举。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
enumTextAlignment: Int{ case left =20 case right =30 case center =50 } //枚举成员转换成原始值 let myRawValue =TextAlignment.left //myRawValue为20
//由原始值获取枚举成员 let textRawValue =60 iflet myAlignment =TextAlignment(rawValue: textRawValue){ //转化成功 print("successfully converted \(textRawValue) into a TextAlignment") }else{ //转化失败 print("\(textRawValue) has no corresponding TextAlignment case") }
enumProgrammingLanguage: String{ case swift ="swift" case objectiveC ="Objective-C" case c ="c" case java ="java" } // 这里可以只给objectiveC指定原始值,因为其他case默认原始值和指定的值完全一样。 enumProgrammingLanguage: String{ case swift case objectiveC ="Objective-C" case c case java }
enumLightbulb{ case on case off // 获取表面温度 funcsurfaceTemperature(forAmbientTemperatureambient: Double) -> Double{ switchself{ case .on: return ambient +150 case .off: return ambient } } // 开关方法:对self进行修改的方法需要用mutating标记 mutatingfunctoggle(){ switchself{ case .on: self= .off case .off: self= .on } } }
var bulb =Lightbulb.on var ambientTemperature =77.0 var bulbTemperature = bulb.surfaceTemperature(forAmbientTemperature:ambientTemperature) print("the bulb's surface temperature is \(bulbTemperature)")
enumShapeDimensions{ case square(side: Double)// 正方形的关联值:边长 case rectangle(width: Double, height: Double)// 长方形的关联值:宽高 case point funcarea()->Double{ switchself{ case .square(side: side): return side * side case .rectangle(width: width, height: height): return width * height case .point return0 } } }
var squareShape =ShapeDimensions.square(side: 12.0) var rectShape =ShapeDimensions.rectangle(width: 3.0, height: 5.0) var pointShape =ShapeDimensions.point print("point's area = \(pointShape.area())")
enumBarcode{ case upc(Int,Int,Int,Int) case qrCode(String) }
var productCode =Barcode.upc(8,83734,75744,4) //同一个商品可以被分配一个不同类型的条形码 productCode = .qrCode("ABCDEGH")
switch productBarcode{ case .upc(let numberSystem, let manufacturer, let product, let check): print("UPC:\(numberSystem), \(manufacturer), \(product), \(check).") case .qrCode(let productCode): print("QR code:\(productCode)") }