8.枚举 Enumerations Swift官方文档——版纳的
2018-03-28 本文已影响0人
KevinFromChina
//: Playground - noun: a place where people can play
import UIKit
// # 枚举
// 枚举中不能定义存储变量,但可以有计算变量、方法以及初始化器.???
// 枚举合集???
/* 枚举与可选的关系,例如Int?
enum Optional {
case none
case some(Int) // 后者是some的关联值
}
*/
// # 枚举语法
enum CompassPoint {
case north
case south
case east, west
}
var a: CompassPoint = .east
var directionToHead = CompassPoint.west
directionToHead = .north
// # 使用Switch语句来匹配枚举
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")
}
// # 关联值
// 类似于元组
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(code: String)
}
var productBarcode = Barcode.upc(8, 85909, 51226, 3)
productBarcode = .qrCode(code: "myURL")
// 用switch提取关联值
switch productBarcode {
case .upc(let numberSystem, let manufacturer, let product, let check):
print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case .qrCode(let productCode): // let can also be var
print("QR code: \(productCode).")
}
// 全部提取成一样的let或var
switch productBarcode {
case let .upc(numberSystem, manufacturer, product, check):
print("UPC : \(numberSystem), \(manufacturer), \(product), \(check).")
case let .qrCode(productCode):
print("QR code: \(productCode).")
}
// # 原始值
// 在定义枚举的时候设定
enum ASCIIControlCharacter: Character {
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
}
// 当整型被用作原始值时,隐式地从0开始依次加一,也可以为第一个成员设定值,然后依次自动加
enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus,neptune
}
// 如果是字符串被用于原始值,那么每一个成员的隐式原始值则是那个成员的名称
// 访问原始值
let aCharacter = ASCIIControlCharacter.carriageReturn.rawValue
// trick:从原始值初始化,返回可选
let possiblePlanet = Planet(rawValue: 7)
// # 枚举递归***
// 定义:有成员的关联值类型是枚举本身,在枚举定义的case前加上indirect,或者在enum关键字前加上indirect.此后枚举就支持递归了
indirect enum ArithmeticExpression {
case number(Int)
case addition(ArithmeticExpression, ArithmeticExpression)
case multiplication(ArithmeticExpression, ArithmeticExpression)
}
// 计算(5 + 4) * 2
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)
}
}
evaluate(product)