Swift心得笔记之控制流
控制流基本上大同小异,在此列举几个比较有趣的地方。
switch
Break
文档原文是NoImplicitFallthrough,粗暴的翻译一下就是:不存在隐式贯穿。其中Implicit是一个经常出现的词,中文原意是:“含蓄的,暗示的,隐蓄的”。在Swift中通常表示默认处理。比如这里的隐式贯穿,就是指传统的多个case如果没有break就会从上穿到底的情况。再例如implicitlyunwrappedoptionals,隐式解析可选类型,则是默认会进行解包操作不用手动通过!进行解包。
回到switch的问题,看下下面这段代码:
letanotherCharacter:Character="a"
switchanotherCharacter{
case"a":
println("Thelettera")
case"A":
println("TheletterA")
default:
println("NottheletterA")
}
可以看到虽然匹配到了case"a"的情况,但是在当前case结束之后便直接跳出,没有继续往下执行。如果想继续贯穿到下面的case可以通过fallthrough实现。
Tuple
我们可以在switch中使用元祖(tuple)进行匹配。用_表示所有值。比如下面这个例子,判断坐标属于什么区域:
letsomePoint=(1,1)
switchsomePoint{
case(0,0)://位于远点
println("(0,0)isattheorigin")
case(_,0)://x为任意值,y为0,即在X轴上
println("(\(somePoint.0),0)isonthex-axis")
case(0,_)://y为任意值,x为0,即在Y轴上
println("(0,\(somePoint.1))isonthey-axis")
case(-2...2,-2...2)://在以原点为中心,边长为4的正方形内。
println("(\(somePoint.0),\(somePoint.1))isinsidethebox")
default:
println("(\(somePoint.0),\(somePoint.1))isoutsideofthebox")
}
//"(1,1)isinsidethebox"
如果想在case中用这个值,那么可以用过值绑定(valuebindings)解决:
letsomePoint=(0,1)
switchsomePoint{
case(0,0):
println("(0,0)isattheorigin")
case(letx,0):
println("xis\(x)")
case(0,lety):
println("yis\(y)")
default:
println("default")
}
Where
case中可以通过where对参数进行匹配。比如我们想打印y=x或者y=-x这种45度仰望的情况,以前是通过if解决,现在可以用switch搞起:
letyetAnotherPoint=(1,-1)
switchyetAnotherPoint{
caselet(x,y)wherex==y:
println("(\(x),\(y))isonthelinex==y")
caselet(x,y)wherex==-y:
println("(\(x),\(y))isonthelinex==-y")
caselet(x,y):
println("(\(x),\(y))isjustsomearbitrarypoint")
}
//"(1,-1)isonthelinex==-y”
ControlTransferStatements
Swift有四个控制转移状态:
continue-针对loop,直接进行下一次循环迭代。告诉循环体:我这次循环已经结束了。
break-针对controlflow(loop+switch),直接结束整个控制流。在loop中会跳出当前loop,在switch中是跳出当前switch。如果switch中某个case你实在不想进行任何处理,你可以直接在里面加上break来忽略。
fallthrough-在switch中,将代码引至下一个case而不是默认的跳出switch。
return-函数中使用
其他
看到一个有趣的东西:SwiftCheatSheet,里面是纯粹的代码片段,如果突然短路忘了语法可以来看看。
比如ControlFlow部分,有如下代码,基本覆盖了所有的点:
//forloop(array)
letmyArray=[1,1,2,3,5]
forvalueinmyArray{
ifvalue==1{
println("One!")
}else{
println("Notone!")
}
}
//forloop(dictionary)
vardict=[
"name":"SteveJobs",
"title":"CEO",
"company":"Apple"
]
for(key,value)indict{
println("\(key):\(value)")
}
//forloop(range)
foriin-1...1{//[-1,0,1]
println(i)
}
//use..toexcludethelastnumber
//forloop(ignoringthecurrentvalueoftherangeoneachiterationoftheloop)
for_in1...3{
//Dosomethingthreetimes.
}
//whileloop
vari=1
whilei<1000{
i*=2
}
//do-whileloop
do{
println("hello")
}while1==2
//Switch
letvegetable="redpepper"
switchvegetable{
case"celery":
letvegetableComment="Addsomeraisinsandmakeantsonalog."
case"cucumber","watercress":
letvegetableComment="Thatwouldmakeagoodteasandwich."
caseletxwherex.hasSuffix("pepper"):
letvegetableComment="Isitaspicy\(x)?"
default://required(inordertocoverallpossibleinput)
letvegetableComment="Everythingtastesgoodinsoup."
}
//Switchtovalidateplistcontent
letcity:Dictionary<String,AnyObject>=[
"name":"Qingdao",
"population":2_721_000,
"abbr":"QD"
]
switch(city["name"],city["population"],city["abbr"]){
case(.Some(letcityNameasNSString),
.Some(letpopasNSNumber),
.Some(letabbrasNSString))
whereabbr.length==2:
println("CityName:\(cityName)|Abbr.:\(abbr)Population:\(pop)")
default:
println("Notavalidcity")
}
以上所述就是本文的全部内容了,希望大家能够喜欢。