//: Playground - noun: a place where people can play
import UIKit
/* switch
*
注意事项:
1.case后必须有可执行语句,否则报错--swichOne
2.case后不需要加break,执行后会自动跳出--swichOne
3.多个case比对条件,用“,”隔开--swichOne
4.case后可以用范围作为匹配条件--swichTwo
5.switch需要处理所有情况,所以default必须要有
6.case可以用来匹配元组--swichOThree
7.case可以数值绑定,将匹配值传递给case后的语句使用--swichOFour
8.case中可以加where判断。。。。--switchFive
9.fallthrough,case匹配后继续执行后面的case或default,fallthrough后面的case或default不能定义变量或者常亮--switchSix
*
*/
//1.case后必须有可执行语句,否则报错--swichOne
//2.case后不需要加break,执行后会自动跳出--swichOne
//3.多个case比对条件,用“,”隔开--swichOne
var swichOne = "C"
switch swichOne {
case "A":
print("A")
case "B", "C":
print("B")
default:
print("错误")
}
// 4.case后可以用范围作为匹配条件--swichTwo
var swichOTwo = 95
switch swichOTwo {
case 90...100:
print("A")
default:
print("错误")
}
// 6.case可以用来匹配元组--swichOThree
var swichOThree = (1, 1)
switch swichOThree {
case (_, 1) :
print("A")
default:
print("错误")
}
//7.case可以数值绑定,将匹配值传递给case后的语句使用--swichOFour
var switchFour = (10, 50);
switch switchFour {
case var (a, b):
print(a, b)
default:
print("错误")
}
// 8.case中可以加where判断。。。。--switchFive
var switchFive = (20, 50);
switch switchFive {
case var (a, b) where a == 10:
print(a)
case var (a, b) where b == 50:
print(b)
default:
print("错误")
}
// 9.fallthrough,case匹配后继续执行后面的case或default,fallthrough后面的case或default不能定义变量或者常量--switchSix
var switchSix = (10, 50);
switch switchSix {
case var (a, b) where a == 10:
print(a)
fallthrough
case (_, 50):
print("haha")
fallthrough
default:
print("错误")
}
swift中switch的使用及注意事项
最新推荐文章于 2024-04-29 00:15:00 发布