swift中switch的使用及注意事项

//: 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("错误")  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值