枚舉語法(Enumeration Syntax)
//使用enum關(guān)鍵詞來創(chuàng)建枚舉并且把它們的整個定義放在一對大括號內(nèi):
enum SomeEnumeration {
//枚舉定義放在這
}
//下面使用枚舉表示指南針?biāo)膫€方向的例子:
enum CompassPoint {
case North
case South
case East
case West
}
//枚舉中定義的值(如North,South,EAST和West)是這個枚舉的成員值(或成員).使用case關(guān)鍵字來定義一個新的枚舉成員值
注意:與C和OC不同,Swift的枚舉成員在被創(chuàng)建時不會被賦予一個默認(rèn)的整型.在上面的CompassPoint例子中,North,South,East和West不會被飲食的復(fù)制為0,1,2,3.相反,這些枚舉成員本身就是完備的值,這些值的類型是已經(jīng)明確定義好的CompassPoint類型.
//多個成員值可以出現(xiàn)在同一行上,用逗號隔開:
enum Planet {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Nepture
}
//每個枚舉定義了一個全新的類型,就像Swift中其他類型一樣,它們的名字(例如:CompassPoint和Planet)必須以一個大寫字母開頭.給枚舉類型起一個單數(shù)名字而不是附屬名字,以便于讀起來更加容易理解:
var directionToHead = CompassPoint.West
//directionToHead的類型可以在它被CompassPoint的某個值初始化時推斷出來.一旦directionToHead被聲明為CompassPoint類型,可以使用更短的點(diǎn)語法將其而何志偉另一個CompassPoint的值
directionToHead = .East
//當(dāng)directionToHead的類型已知時,再次為其賦值可以省略枚舉類型名.在使用具有顯式類型的枚舉值時,這種寫法讓代碼具有更好的可讀性.
使用Switch語句匹配枚舉值
//可以使用switch語句匹配單個枚舉值:
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")
}
//正如在控制流(Control Flow)中介紹的那樣,在判斷一個枚舉而理性的值時,switch語法必須窮舉所有情況.如果忽略了.West這種情況,上面代碼將無法通過編譯,因為它沒有考慮到CompassPoint的所有成員.強(qiáng)制窮舉確保了枚舉成員不會被意外遺漏.
//當(dāng)不需要匹配每個枚舉成員的時候,可以提供一個default分支來涵蓋所有的未明確處理的枚舉成員:
let somePlant = Planet.Earth
switch somePlant {
case .Earth:
print("Mostly harmless")
default:
print("Not a safe place for humens")
}
//注意:當(dāng)已經(jīng)窮舉完所有情況時,就不能用default,如果用會提示"Default will never be executed"
關(guān)聯(lián)值(Associated Values)
//定義關(guān)聯(lián)值枚舉
enum Barcode {
case UPCA(Int, Int, Int, Int)
case QRCode(String)
}
//然后可以使用任意一種條形碼類型創(chuàng)建新的條形碼.例如:
var productBarcode = Barcode.UPCA(8, 66666, 55555, 3)
//同一個商品可以被分配一個不同類型的條形碼.例如:
productBarcode = .QRCode("ABCDEFGHIJK")
//這時原始的Barcode.UPCA和氣證書關(guān)聯(lián)值給新的`Barcode.QRCode`所替代.也就是說這個枚舉中只能存儲`.UPCA`或者`.QRCode`中的一個
//用switch檢查不同的條形碼的類型
switch productBarcode {
case .UPCA(let numberSystem, let manufacturer, let product, let check):
print("UPC-A:\(numberSystem),\(manufacturer),\(product),\(check)")
case .QRCode(let productCode):
print("QR code: \(productCode)")
}
//如果枚舉成員的所有關(guān)聯(lián)值被提取為常量,或者都被提取為變量,為了簡潔,可以在成員名稱前標(biāo)注一個let或者var
switch productBarcode {
case let .UPCA(numberSystem, manufacturer, product, check):
print("UPC-A:\(numberSystem),\(manufacturer),\(product),\(check)")
case let .QRCode(productCode):
print("QR code: \(productCode)")
}
原始值
//作為關(guān)聯(lián)值的替代選擇,枚舉成員可以被默認(rèn)值(稱為原始值)預(yù)填充,但是這些原始值的類型必須相同.
enum ASCIIControlCharacter: Character {
case Tab = "\t"
case LineFeed = "\n"
case CarriageReturn = "\r"
}
//原始值的隱式賦值(Implicitly Assigned Raw Values)
enum Planet1: Int {
case Mercury = 1,Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
//枚舉的細(xì)化,使用字符串類型的原始值表示各個方向的名稱
enum CompassPoint1: String {
case North, South, East, West
}
//使用枚舉成員的rawValue屬性可以訪問該枚舉成員的原始值
let earthsOrder = Planet1.Earth.rawValue//值為3
let sunsetDirection = CompassPoint1.West.rawValue//值為West
//使用原始值初始化枚舉實例(Initializing from a Raw Value)
let possiblePlanet = Planet1(rawValue: 7)
print(possiblePlanet!)
//可選綁定(optional binding)
let positionToFind = 9
if let somePlanet = Planet1(rawValue: 9) {
switch somePlant {
case .Earth:
print("Mostly harmless")
default:
print("Not a safe place for humans")
}
} else {
print("There isn't a planet at position \(positionToFind)")
}
遞歸枚舉
//枚舉類型存儲簡單的算術(shù)表達(dá)式
enum ArithmeticExpression {
case Number(Int)
indirect case Addition(ArithmeticExpression, ArithmeticExpression)
indirect case Multiplication(ArithmeticExpression, ArithmeticExpression)
}
//也可以在枚舉類型開頭加上關(guān)鍵字indirect來表明它的所有成員都是可遞歸的:
indirect enum ArithmeticExpression {
case Number(Int)
case Addition(ArithmeticExpression, ArithmeticExpression)
case Multiplication(ArithmeticExpression, ArithmeticExpression)
}
//對算數(shù)表達(dá)式求值的函數(shù):
func evaluate(expression: ArithmeticExpression) -> Int {
switch expression {
case .Number(let value):
return value
case .Addition(let left, let right):
return evaluate(left) + evaluate(right)
case .Multiplication(let left, let right):
return evaluate(left) * evaluate(right)
}
}
//計算(5+4)*2
let five = ArithmeticExpression.Number(5)
print(evaluate(five))
let four = ArithmeticExpression.Number(4)
let sum = ArithmeticExpression.Addition(five, four)
let product = ArithmeticExpression.Multiplication(sum, ArithmeticExpression.Number(2))
print(evaluate(product))
//該函數(shù)如果遇到純數(shù)字,就直接返回該數(shù)字的值。如果遇到的是加法或乘法運(yùn)算,則分別計算左邊表達(dá)式和右邊表達(dá)式的值,然后相加或相乘。
本文來自:上善若水
--EOF--