1. 在Swift和Java關於枚舉方面,兩個語言語法類似。less
Swift定義枚舉:ide
enum CompassPoint{ case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune }
Java定義枚舉:函數
public enum ColorSelect { red, green, yellow, blue; }
2. 枚舉和switch結合使用this
Swift代碼以下:spa
enum CompassPoint{ case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune } let directionToHead = CompassPoint.Venus switch directionToHead { case CompassPoint.Earth : print("this is \(directionToHead)") case CompassPoint.Venus : print("this is \(directionToHead)") case CompassPoint.Mercury : print("this is \(directionToHead)") case CompassPoint.Jupiter : print("this is \(directionToHead)") }
2.1 switch
的 case 分支代碼中提取每一個相關值做爲一個常量(用let
前綴)或者做爲一個變量(用var
前綴)來使用:代碼以下:code
enum Barcode { case UPCA(Int, Int, Int) case QRCode(String) } var productBarcode = Barcode.UPCA(8, 85909_51226, 3) productBarcode = .QRCode("ABCDEFGHIJKLMNOP") switch productBarcode { case let .UPCA(numberSystem, identifier, check): print("UPC-A with value of \(numberSystem), \(identifier), \(check).") case let .QRCode(productCode): print("QR code with value of \(productCode).") } // 輸出 "QR code with value of ABCDEFGHIJKLMNOP."
2.2 原始值(Raw Values):枚舉成員能夠被默認值(稱爲原始值)預先填充,其中這些原始值具備相同的類型。blog
enum ASCIIControlCharacter: Character { case Tab = "\t" case LineFeed = "\n" case CarriageReturn = "\r" }
原始值能夠是字符串,字符,或者任何整型值或浮點型值。每一個原始值在它的枚舉聲明中必須是惟一的。當整型值被用於原始值,若是其餘枚舉成員沒有值時,它們會自動遞增。字符串
enum Planet: Int { case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune }
使用枚舉成員的rawValue
屬性能夠訪問該枚舉成員的原始值,經過參數爲rawValue
構造函數建立特定原始值的枚舉。代碼以下:it
let earthsOrder = Planet.Earth.rawValue // earthsOrder is 3 let possiblePlanet = Planet(rawValue: 7) // possiblePlanet is of type Planet? and equals Planet.Uranus
然而,並不是全部可能的Int
值均可以找到一個匹配的行星。正由於如此,構造函數能夠返回一個可選的枚舉成員。在上面的例子中,possiblePlanet
是Planet?
類型,或「可選的Planet
」。io
若是你試圖尋找一個位置爲9的行星,經過參數爲rawValue
構造函數返回的可選Planet
值將是nil
:
enum Planet: Int { case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune } let positionToFind = 9 if let somePlanet = Planet(rawValue: positionToFind) { switch somePlanet { case .Earth: print("Mostly harmless") default: print("Not a safe place for humans") } } else { print("There isn't a planet at position \(positionToFind)") }
這個範例使用可選綁定(optional binding),經過原始值9
試圖訪問一個行星。if let somePlanet = Planet(rawValue: 9)
語句得到一個可選Planet
,若是可選Planet
能夠被得到,把somePlanet
設置成該可選Planet
的內容。在這個範例中,沒法檢索到位置爲9
的行星,因此else
分支被執行。