swift where与匹配模式的实例详解
swiftwhere与匹配模式的实例详解
前言:
在众多Swift提供给Objective-C程序员使用的新特性中,有个特性把自己伪装成一个无聊的老头,但是却在如何优雅的解决“鞭尸金字塔“的问题上有着巨大的潜力。很显然我所说的这个特性就是switch语句,对于很多Objective-C程序员来说,除了用在Duff'sDevice上比较有趣之外,switch语句非常笨拙,与多个if语句相比,它几乎没有任何优势。
1、基本使用
Swift中switch语句case后面可以用where对条件进行限制
letpoint=(3,3)
switchpoint{
caselet(x,y)wherex==y:
print("It'sonthelinex==y!")
caselet(x,y)wherex==-y:
print("It'sonthelinex==-y!")
caselet(x,y):
print("It'sjustanordinarypoint.")
print("Thepointis(\(x),\(y))")
}
2、使用if-case-where语句替代switch语句的使用方法
letage=19
switchage{
case10...19:
print("You'reateenager.")
default:
print("You'renotateenager.")
}
ifcase10...19=age{
print("You'reateenager.")
}
ifcase10...19=agewhereage>=18{
print("You'reateenagerandinacollege!")
}
注意:case条件必须放在”=”之前
swift3.0以后ifcase后面的”where”用”,”代替
3、if-case与元组组合使用(元组解包使用)
letvector=(4,0)
ifcase(letx,0)=vectorwherex>2&&x<5{
print("It'sthevector!")
}
4、case-where与循环组合使用
foriin1...100{
ifi%3==0{
print(i)
}
}
forcaseletiin1...100wherei%3==0{
print(i)
}
使用case限制条件可以大大减少代码量,使用起来非常方便,是swift语言的一大特色,好好掌握可以写出很优美的简洁的代码
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!