Swift-流程控制器switch

2020-11-17  本文已影响0人  守护地中海的花
image.png

简易代码

var number = 1
switch number {
case 0:
    print("0")
case 1:
    print("1")
default:
    print("default")
}

fallthrough贯穿

var number = 1
switch number {
case 0:
    print("0")
case 1:
    print("1")
    fallthrough
default:
    print("default")
}

控制台打印:
1
default

如果能保证已处理所有情况,也可以不必使用default

enum Answer {case right,wrong}
let answer = Answer.right
switch answer {
case Answer.right:
    print("对")
case Answer.wrong:
    print("错误")
}

复合条件

switch也支持Character、String类型

let name = "jack"
switch name {
case "Jack":
    print("我是 Jack")
case "jack":
    print("我是 jack")
default:
    break
}

区间匹配、元组匹配

let count = 2
switch count {
case 1...2:
    print("1...2")
default:
    break
}

let map = (x:1,y:2)
switch map {
case (1,2):
    print(map)
    fallthrough
case (-2...2,-2...2):
    print(map)
    fallthrough
case (_,_):
    print(map)
default:
    break
}

值绑定

let point = (2,2)
switch point {
case (let x, 0):
    print("\(x),0")
case let (x,y) where x == y :
    print("x=y")
default:
    break;
}
上一篇下一篇

猜你喜欢

热点阅读