Control Flow 控制流
For循环
for-in遍历一个集合里面的所有元素,index使用前不需要声明,只需包含在循环的声明中即可
- forindexin1...5{
- println("(index)times5is(index*5)")
- }
-
-
- //3times5is15
- //4times5is20
- //5times5is25
如果不知道区间内每一项的值,使用下划线 _ 来替代变量名去忽略,以下计算base的power次幂,这个例子不需要知道每一次循环中的具体值,只需知道需要循环的次数,使用下划线能够忽略具体的值,且不提供循环遍历时对值的访问
letbase=3
- letpower=10
- varanswer=1
- for_in1...power{
- answer*=base
- }
- println("(base)tothepowerof(power)is(answer)")
- //prints"3tothepowerof10is59049"
遍历数组
letnames=["Anna","Alex","Brian","Jack"]
- fornameinnames{
- println("Hello,(name)!")
- //Hello,Anna!
遍历字典
字典的每项以(key,value)元素组返回,在for-in循环中用显式的常量解读,因为字典是无序的,所以循环输出也是无序的
letnumberOfLegs=["spider":8,"ant":6,"cat":4]
- for(animalName,legCount)innumberOfLegs{
- println("(animalName)shave(legCount)legs")
- //spidershave8legs
- //antshave6legs
- //catshave4legs
另一种for循环方式,条件判断和循环递增,执行顺序是先初始化 initialization,然后判断条件condition,如果为true执行语句statements,然后进行increment操作,再循环condition
forinitialization;condition;increment{
- statements
- //等同于
- initialization
- whilecondition{
- statements
- increment
-
- forvarindex=0;index<3;++index{
- println("indexis(index)")
- //indexis0
- //indexis1
- //indexis2
While循环
适合在第一次条件未知的情况下使用,循环一直到条件变成false,两种形式,while , do-while
whilecondition{
- //do-while形式就是在执行while里面的判断时,首先执行一次循环的代码,保证了循环至少执行一次
- do{
- }whilecondition
//翻译到这里原文好像开始玩起游戏来了。。。省略
条件语句
Swift提供if和switch语句,if用于条件简单且情况略少的时候,switch用于比较复杂和情况略多的时候
if: 只包含一个条件,条件为true,执行之
vartemperatureInFahrenheit=30
- iftemperatureInFahrenheit<=32{
- println("It'sverycold.Considerwearingascarf.")
- //prints"It'sverycold.Considerwearingascarf."
-
- temperatureInFahrenheit=90
- iftemperatureInFahrenheit<=32{
- println("It'sverycold.Considerwearingascarf.")
- elseiftemperatureInFahrenheit>=86{
- println("It'sreallywarm.Don'tforgettowearsunscreen.")
- else{
- println("It'snotthatcold.Wearat-shirt.")
- //prints"It'sreallywarm.Don'tforgettowearsunscreen."
switch:尝试把某个值与若干个条件进行比较,条件的值的类型都是相同的,switch语句由多个case构成,每个case都是代码的一条分支,在无法满足所有条件的情况下使用default
switchsomevaluetoconsider{
- casevalue1:
- respondtovalue1
- casevalue2,
- value3:
- respondtovalue2or3
- default:
- otherwise,dosomethingelse
- }
当匹配的case执行完后,程序会终止switch语句,不再执行下一个case,所以可以省略break关键字
每个case必须包含至少一条语句,否则编译不通过,避免了从一个case分支贯穿到另一个case,让代码更安全
letanotherCharacter:Character="a"
- switchanotherCharacter{
- case"a":
- case"A":
- println("TheletterA")
- default:
- println("NottheletterA")
- //thiswillreportacompile-timeerror
一个case也可以由多种情况,用逗号分开
casevalue1,0); background-color:inherit">2:
- }
case也可以用于区间
letcount=3_000_000_000_000
- letcountedThings="starsintheMilkyWay"
- varnaturalCount:String
- switchcount{
- case0:
- naturalCount="no"
- case1...3:
- naturalCount="afew"
- case4...9:
- naturalCount="several"
- case10...99:
- naturalCount="tensof"
- case100...999:
- naturalCount="hundredsof"
- case1000...999_999:
- naturalCount="thousandsof"
- naturalCount="millionsandmillionsof"
- println("Thereare(naturalCount)(countedThings).")
- //prints"TherearemillionsandmillionsofstarsintheMilkyWay."
switch中使用元组
letsomePoint=(1,1)
- switchsomePoint{
- case(0,0):
- println("(0,0)isattheorigin")
- case(_,248)"> println("((somePoint.0),0)isonthex-axis")
- )
- case(-2...2,-2...2):
- )
- )
- //prints"(1,1)isinsidethebox"
值绑定
,在case里临时新建一个变量,在分支里引用
letanotherPoint=(2,0)
- switchanotherPoint{
- case(letx,248)"> println("onthex-axiswithanxvalueof(x)")
- println("onthey-axiswithayvalueof(y)")
- caselet(x,y):
- println("somewhereelseat((x),(y))")
- //prints"onthex-axiswithanxvalueof2"
在case里使用where
,多加一个动态的过滤器,仅当case成立且where条件为true,才执行
letyetAnotherPoint=(1,-1)
- switchyetAnotherPoint{
- y:
- println("((x),(y))isonthelinex==y")
- )
- )
控制传递语句
控制代码的跳转,改变程序的执行顺序 continue 告诉一个循环体立刻停止本次循环,重新开始下一次循环
letpuzzleInput="greatmindsthinkalike"
- varpuzzleOutput=""
- forcharacterinpuzzleInput{
- switchcharacter{
- case"a","e","i","o","u","":
- continue
- default:
- puzzleOutput+=character
- println(puzzleOutput)
- //prints"grtmndsthnklk"
break
结束当前循环
numberSymbol:Character="三"
- varpossibleIntegerValue:Int?
- switchnumberSymbol{
- case"1","?","一","?":
- possibleIntegerValue=1
- case"2","?","二","?":
- possibleIntegerValue=2
- case"3","?","三","?":
- possibleIntegerValue=3
- case"4","?","四","?":
- possibleIntegerValue=4
- break
- ifletintegerValue=possibleIntegerValue{
- println("Theintegervalueof(numberSymbol)is(integerValue).")
- println("Anintegervaluecouldnotbefoundfor(numberSymbol).")
- //prints"Theintegervalueof三is3."
贯穿 (Fallthrough)
Swift中的switch不会从上一个case里运行到下一个case里,只要第一个匹配的case执行完后,整个swtich代码就执行完了,而C语言需要break来防止这种现象,否则将会一直执行下去,如果需要C语言的这种特性,使用fallthrough关键字 fallthrough关键字不会检查它下一个落入执行case中的匹配条件,只会简单的使代码继续执行到下一个case中的代码
letintegerToDescribe=5
- vardescription="Thenumber(integerToDescribe)is"
- switchintegerToDescribe{
- case2,3,5,7,11,13,17,19:
- description+="aprimenumber,andalso"
- fallthrough
- description+="aninteger."
- println(description)
- //prints"Thenumber5isaprimenumber,andalsoaninteger."
带标签的语句 (Labeled Statements)
在循环体和switch代码中嵌套循环体和switch代码来创造复杂的控制流,因为都可以用break结束整个方法体,所以显式的指出需要终止哪个循环体或swtich是必要的,类似,显式指出continue想要影响哪个循环体也是有用的 通过使用标签来标记一个循环体或switch,标签后带一个冒号
labelname: }
以下例子来源于一个游戏例子,游戏的规则跟飞行棋类似,25个格子然后掷骰子,按掷的骰子走相应的步数,走到某些格子会前进几步或后退几步,走完25个或超过为赢家
letfinalSquare=25
- varboard=Int[](count:finalSquare+1,0); background-color:inherit">repeatedValue:0)
- board[03]=+08;board[06]=+11;board[09]=+09;board[10]=+02
- board[14]=-10;board[19]=-11;board[22]=-02;board[24]=-08
- varsquare=0
- vardiceRoll=0
- gameLoop:whilesquare!=finalSquare{
- if++diceRoll==7{diceRoll=1}
- switchsquare+diceRoll{
- finalSquare:
- //diceRollwillmoveustothefinalsquare,sothegameisover
- breakgameLoop
- caseletnewSquarewherenewSquare>finalSquare:
- //diceRollwillmoveusbeyondthefinalsquare,sorollagain
- continuegameLoop
- //thisisavalidmove,sofindoutitseffect
- square+=diceRoll
- square+=board[square]
- println("Gameover!")
如果上述的break语句没有使用标签,那将会中断switch而不是while,使用标签能清晰的表明break想要中断哪个循环 (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|