更加强大的switch

2021-06-20  本文已影响0人  一个栗

没有隐式贯穿

char c = 'z';
    switch (c) {
        case 'a':
            NSLog(@"the first");
        case 'z':
            NSLog(@"the last");
        default:
            NSLog(@"other");
    }

运行结果如下:
the last
other

Swift 代码

let someCahracter:Character = "z"
switch someCahracter {
case "a":
    print("the first")
case "z":
    print("the last")
default:
    print("other")
}

运行结果如下:
the last
let someCahracter:Character = "a"
switch someCahracter {
case "a","A":
    print("the first")
case "z":
    print("the last")
default:
    print("other")
}

运行结果如下:
the first

区间匹配

let approximateCount = 62
let countedThings = "moons orbiting Saturn"
var naturalCount:String
switch approximateCount {
case 0:
    naturalCount = "no"
case 1..<5:
    naturalCount = "a few"
case 5..<12:
    naturalCount = "several"
case 12..<100:
    naturalCount = "dozens of"
case 100..<1000:
    naturalCount = "hundreds of"
default:
    naturalCount = "many"
}
print("there are \(naturalCount) \(countedThings).")

运行结果如下:
there are dozens of moons orbiting Saturn.

元组匹配

let somePoint = (1,1)
switch somePoint {
case (0,0):
    print("(0,0) is at the origin")
case (_,0):
    print("\(somePoint.0), 0) is at the x-axis")
case (0,_):
    print("(0,\(somePoint.0)) is at the y-axis")
case (-2...2, -2...2):
        print("(\(somePoint.0),\(somePoint.1)) is inside of the box")
default:
    print("(\(somePoint.0),\(somePoint.1)) is outside of the box")
}

运行结果如下:
(1,1) is inside of the box

值绑定

let anotherPoint = (2,1)
switch anotherPoint {
case (let x,0):
    print("on the x-axis with an x value of \(x)")
case (0, let y):
    print("on the y-axis with an y value of \(y)")
case let(x, y):
    print("somewhere else at (\(x),\(y))")
}

运行结果如下:
somewhere else at (2,1)

where 字句

let yetAnotherPoint = (1,-1)
switch yetAnotherPoint {
case let(x, y) where x == y :
    print("(\(x),\(y)) is on the line x == y")
case let(x, y) where x == -y :
    print("(\(x),\(y)) is on the line x == -y")
case let(x, y):
    print("(\(x),\(y)) is just some arbitrary point")
}

运行结果如下:
(1,-1) is on the line x == -y

复合匹配

let someCahracter:Character = "e"
switch someCahracter {
case "a","e","i","o","u":
    print("\(someCahracter) is a vowel")
case "b","c","d","f","g","h","j","k","l","m",
     "n","p","q","r","s","t","v","w","x","y","z":
    print("\(someCahracter) is a consonant")
default:
    print("\(someCahracter) is not a vowel or a consonant")
}

运行结果如下:
e is a vowel

复合匹配-值绑定

let stillAnotherPoint = (9,0)
switch stillAnotherPoint {
case (let distance, 0),(0, let distance) :
    print("on an sxis, \(distance) from the origin")
default:
    print("Not on an axis")
}

运行结果如下:
on an sxis, 9 from the origin
上一篇 下一篇

猜你喜欢

热点阅读