swift2 枚舉類型

枚舉語法


enum CompassPoint {
    case North
    case South
    case East
    case West
}
var directionToHead = CompassPoint.West
directionToHead = .South

directionToHead的類型被推斷當它被CompassPoint的一個可能值初始化。
一旦directionToHead被聲明爲一個CompassPoint,你可以使用更短的點(.)語法將其設置爲另一個CompassPoint的值.


匹配枚舉值


enum CompassPoint {
    case North
    case South
    case East
    case West
}
var directionToHead = CompassPoint.West

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”


相關值


enum Barcode {
    case UPCA(Int, Int, Int)
    case QRCode(String)
}
var productBarcode = Barcode.UPCA(8, 85909_51226, 3)
productBarcode = .QRCode("ABCDEFGHIJKLMNOP")

switch productBarcode {
case .UPCA(let numberSystem, let identifier, let check):
    print("UPC-A with value of \(numberSystem), \(identifier), \(check).")
case .QRCode(let productCode):
    print("QR code with value of \(productCode).")
}
// 輸出 "QR code with value of ABCDEFGHIJKLMNOP.”

如果一個枚舉成員的所有相關值被提取爲常量,或者它們全部被提取爲變量,爲了簡潔,你可以只放置一個var或者let標註在成員名稱前:

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."



原始值


enum Planet: Int {
    case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}

let earthsOrder = Planet.Earth.rawValue
// earthsOrder is 3

枚舉類型可以用原始值進行預先填充,上述枚舉的原始值類型爲int
同時可以通過rawValue訪問原始值,可以通過原始值創建枚舉

let possiblePlanet = Planet(rawValue: 7)
// possiblePlanet is of type Planet? and equals Planet.Uranus
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)")
}
// 輸出 "There isn't a planet at position 9

這個範例使用可選綁定(optional binding),通過原始值9試圖訪問一個行星。
if let somePlanet = Planet(rawValue: 9)語句獲得一個可選Planet,如果可選Planet可以被獲得,把somePlanet設置成該可選Planet的內容。
在這個範例中,無法檢索到位置爲9的行星,所以else分支被執行。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章