之前记录了Swift Enumeration(1),这篇算是它的延续吧,继续说下Enumeration,看以下定义
enum TrainStatus {
case OnTime
case Delay(Int) //带关联值
}
var myTrainStatus = TrainStatus.Delay(10)
用Switch 匹配对象
switch myTrainStatus{
case .OnTime:
println("Train is ontime")
case .Delay(let minutes):
println("Train delays \(minutes) minutes")
}
匹配方式是有先后顺序的,上面中先匹配到Delay然后再给里面的minutes赋值,好下面我将演示区间匹配。
switch myTrainStatus{
case .OnTime://匹配准时
println("Train is ontime")
case .Delay(1...5)://匹配1到5
println("Train delays less than five minutes")
case .Delay(6...10)://匹配6到10
println("Train delays between six and ten minutes")
case .Delay(_): //匹配其它,里面是下划线
println("Train delays more than ten minutes")
}
关联值的另一个例子,
enum Barcode{ case UPCA(Int,Int,Int,Int) case QRCode(String) } var productCodeA:Barcode = Barcode.UPCA(10, 20, 30, 40) var productCodeB:Barcode = Barcode.QRCode("This is an infomation") switch productCodeB{ case .UPCA(let a,let b,let c,let d): print("\(a)-\(b)-\(c)-\(d)") case .QRCode(let code): print("\(code)") }