enum CompassPoint{
case north
case south
case east
case west
} Swift中没有默认值 ,在C和OC中north=0,south=1,east=2,west=3
enum Planet{
case mercury,venus,earth,mars,jupiter,saturn,uranus,neptune
}
var directionToHead=CompassPoint.west
directionToHead= .east
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")
}
// Prints "Watch out for penguins"
enum Barcode{
case upc(Int,Int,Int,Int)//条形码
case qrCode(String)//二维码
}
var productBarcode = Barcode.upc(8,85909,51226,3)
productBarcode= .qrCode("ABCDEFGHIJKLMNOP")
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).")
}
// Prints "QR code: ABCDEFGHIJKLMNOP."
Raw Values // 初始值
enum ASCIIControlCharacter:Character{
case tab="\t"
case lineFeed="\n"
case carriageReturn="\r"
}
Implicitly Assigned Raw Values // 隐式分配的原始值
enum Planet:Int{
case mercury=1,venus,earth,mars,jupiter,saturn,uranus,neptune
} // venus=2,后面的一次递增
enum CompassPoint:String{
case north,south,east,west
} // 默认初始值 north = "north" south = "south" 后面雷同
let positionToFind=11
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)")
}
// Prints "There isn't a planet at position 11"
Recursive Enumerations // 递归枚举
enum ArithmeticExpression{
case number(Int)
indirect case addition(ArithmeticExpression,ArithmeticExpression)
indirect case multiplication(ArithmeticExpression,ArithmeticExpression)
}
indirect enum ArithmeticExpression{
case number(Int)
case addition(ArithmeticExpression,ArithmeticExpression)
case multiplication(ArithmeticExpression,ArithmeticExpression)
}
let five=ArithmeticExpression.number(5)
let four=ArithmeticExpression.number(4)
let sum=ArithmeticExpression.addition(five,four)
let product=ArithmeticExpression.multiplication(sum,ArithmeticExpression.number(2))
func evaluate( _ expression:ArithmeticExpression) ->Int{
switch expression{
case let .number(value):
return value
case let .addition(left,right):
return evaluate(left) + evaluate(right)
case let .multiplication(left,right):
return evaluate(left) * evaluate(right)
}
}
print(evaluate(product)) // Prints "18"