Swift 控制流(四)

前端之家收集整理的这篇文章主要介绍了Swift 控制流(四)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Control Flow 控制流

For循环

for-in遍历一个集合里面的所有元素,index使用前不需要声明,只需包含在循环的声明中即可
[objc] view plain copy
  1. forindexin1...5{
  2. println("\(index)times5is\(index*5)")
  3. }
  4. //1times5is5
  5. //2times5is10
  6. //3times5is15
  7. //4times5is20
  8. //5times5is25
如果不知道区间内每一项的值,使用下划线 _ 来替代变量名去忽略,以下计算base的power次幂,这个例子不需要知道每一次循环中的具体值,只需知道需要循环的次数,使用下划线能够忽略具体的值,且不提供循环遍历时对值的访问
    letbase=3
  1. letpower=10
  2. varanswer=1
  3. for_in1...power{
  4. answer*=base
  5. }
  6. println("\(base)tothepowerof\(power)is\(answer)")
  7. //prints"3tothepowerof10is59049"

遍历数组
    letnames=["Anna","Alex","Brian","Jack"]
  1. fornameinnames{
  2. println("Hello,\(name)!")
  3. //Hello,Anna!

遍历字典

字典的每项以(key,value)元素组返回,在for-in循环中用显式的常量解读,因为字典是无序的,所以循环输出也是无序的

    letnumberOfLegs=["spider":8,"ant":6,"cat":4]
  1. for(animalName,legCount)innumberOfLegs{
  2. println("\(animalName)shave\(legCount)legs")
  3. //spidershave8legs
  4. //antshave6legs
  5. //catshave4legs

另一种for循环方式,条件判断和循环递增,执行顺序是先初始化 initialization,然后判断条件condition,如果为true执行语句statements,然后进行increment操作,再循环condition
    forinitialization;condition;increment{
  1. statements
  2. //等同于
  3. initialization
  4. whilecondition{
  5. statements
  6. increment
  7. forvarindex=0;index<3;++index{
  8. println("indexis\(index)")
  9. //indexis0
  10. //indexis1
  11. //indexis2

While循环

适合在第一次条件未知的情况下使用,循环一直到条件变成false,两种形式,while , do-while
    whilecondition{
  1. //do-while形式就是在执行while里面的判断时,首先执行一次循环的代码,保证了循环至少执行一次
  2. do{
  3. }whilecondition
//翻译到这里原文好像开始玩起游戏来了。。。省略

条件语句

Swift提供if和switch语句,if用于条件简单且情况略少的时候,switch用于比较复杂和情况略多的时候

if: 只包含一个条件,条件为true,执行之

    vartemperatureInFahrenheit=30
  1. iftemperatureInFahrenheit<=32{
  2. println("It'sverycold.Considerwearingascarf.")
  3. //prints"It'sverycold.Considerwearingascarf."
  4. temperatureInFahrenheit=90
  5. iftemperatureInFahrenheit<=32{
  6. println("It'sverycold.Considerwearingascarf.")
  7. elseiftemperatureInFahrenheit>=86{
  8. println("It'sreallywarm.Don'tforgettowearsunscreen.")
  9. else{
  10. println("It'snotthatcold.Wearat-shirt.")
  11. //prints"It'sreallywarm.Don'tforgettowearsunscreen."

switch:尝试把某个值与若干个条件进行比较,条件的值的类型都是相同的,switch语句由多个case构成,每个case都是代码的一条分支,在无法满足所有条件的情况下使用default
    switchsomevaluetoconsider{
  1. casevalue1:
  2. respondtovalue1
  3. casevalue2,
  4. value3:
  5. respondtovalue2or3
  6. default:
  7. otherwise,dosomethingelse
  8. }
当匹配的case执行完后,程序会终止switch语句,不再执行下一个case,所以可以省略break关键字
每个case必须包含至少一条语句,否则编译不通过,避免了从一个case分支贯穿到另一个case,让代码更安全
    letanotherCharacter:Character="a"
  1. switchanotherCharacter{
  2. case"a":
  3. case"A":
  4. println("TheletterA")
  5. default:
  6. println("NottheletterA")
  7. //thiswillreportacompile-timeerror

一个case也可以由多种情况,用逗号分开
    casevalue1,0); background-color:inherit">2:
  1. }

case也可以用于区间
    letcount=3_000_000_000_000
  1. letcountedThings="starsintheMilkyWay"
  2. varnaturalCount:String
  3. switchcount{
  4. case0:
  5. naturalCount="no"
  6. case1...3:
  7. naturalCount="afew"
  8. case4...9:
  9. naturalCount="several"
  10. case10...99:
  11. naturalCount="tensof"
  12. case100...999:
  13. naturalCount="hundredsof"
  14. case1000...999_999:
  15. naturalCount="thousandsof"
  16. naturalCount="millionsandmillionsof"
  17. println("Thereare\(naturalCount)\(countedThings).")
  18. //prints"TherearemillionsandmillionsofstarsintheMilkyWay."

switch中使用元组
    letsomePoint=(1,1)
  1. switchsomePoint{
  2. case(0,0):
  3. println("(0,0)isattheorigin")
  4. case(_,248)"> println("(\(somePoint.0),0)isonthex-axis")
  5. )
  6. case(-2...2,-2...2):
  7. Box")
  8. Box")
  9. //prints"(1,1)isinsidetheBox"

值绑定 ,在case里临时新建一个变量,在分支里引用
    letanotherPoint=(2,0)
  1. switchanotherPoint{
  2. case(letx,248)"> println("onthex-axiswithanxvalueof\(x)")
  3. println("onthey-axiswithayvalueof\(y)")
  4. caselet(x,y):
  5. println("somewhereelseat(\(x),\(y))")
  6. //prints"onthex-axiswithanxvalueof2"

在case里使用where ,多加一个动态的过滤器,仅当case成立且where条件为true,才执行
    letyetAnotherPoint=(1,-1)
  1. switchyetAnotherPoint{
  2. y:
  3. println("(\(x),\(y))isonthelinex==y")
  4. )
  5. )

控制传递语句

控制代码的跳转,改变程序的执行顺序

continue
告诉一个循环体立刻停止本次循环,重新开始下一次循环
    letpuzzleInput="greatmindsthinkalike"
  1. varpuzzleOutput=""
  2. forcharacterinpuzzleInput{
  3. switchcharacter{
  4. case"a","e","i","o","u","":
  5. continue
  6. default:
  7. puzzleOutput+=character
  8. println(puzzleOutput)
  9. //prints"grtmndsthnklk"

break
结束当前循环
    numberSymbol:Character="三"//SimplifiedChineseforthenumber3
  1. varpossibleIntegerValue:Int?
  2. switchnumberSymbol{
  3. case"1","١","一","๑":
  4. possibleIntegerValue=1
  5. case"2","٢","二","๒":
  6. possibleIntegerValue=2
  7. case"3","٣","三","๓":
  8. possibleIntegerValue=3
  9. case"4","٤","四","๔":
  10. possibleIntegerValue=4
  11. break
  12. ifletintegerValue=possibleIntegerValue{
  13. println("Theintegervalueof\(numberSymbol)is\(integerValue).")
  14. println("Anintegervaluecouldnotbefoundfor\(numberSymbol).")
  15. //prints"Theintegervalueof三is3."

贯穿 (Fallthrough)

Swift中的switch不会从上一个case里运行到下一个case里,只要第一个匹配的case执行完后,整个swtich代码就执行完了,而C语言需要break来防止这种现象,否则将会一直执行下去,如果需要C语言的这种特性,使用fallthrough关键字
fallthrough关键字不会检查它下一个落入执行case中的匹配条件,只会简单的使代码继续执行到下一个case中的代码
    letintegerToDescribe=5
  1. vardescription="Thenumber\(integerToDescribe)is"
  2. switchintegerToDescribe{
  3. case2,3,5,7,11,13,17,19:
  4. description+="aprimenumber,andalso"
  5. fallthrough
  6. description+="aninteger."
  7. println(description)
  8. //prints"Thenumber5isaprimenumber,andalsoaninteger."

带标签的语句 (Labeled Statements)

在循环体和switch代码中嵌套循环体和switch代码来创造复杂的控制流,因为都可以用break结束整个方法体,所以显式的指出需要终止哪个循环体或swtich是必要的,类似,显式指出continue想要影响哪个循环体也是有用的
通过使用标签来标记一个循环体或switch,标签后带一个冒号
    labelname: }
以下例子来源于一个游戏例子,游戏的规则跟飞行棋类似,25个格子然后掷骰子,按掷的骰子走相应的步数,走到某些格子会前进几步或后退几步,走完25个或超过为赢家
    letfinalSquare=25
  1. varboard=Int[](count:finalSquare+1,0); background-color:inherit">repeatedValue:0)
  2. board[03]=+08;board[06]=+11;board[09]=+09;board[10]=+02
  3. board[14]=-10;board[19]=-11;board[22]=-02;board[24]=-08
  4. varsquare=0
  5. vardiceRoll=0
  6. gameLoop:whilesquare!=finalSquare{
  7. if++diceRoll==7{diceRoll=1}
  8. switchsquare+diceRoll{
  9. finalSquare:
  10. //diceRollwillmoveustothefinalsquare,sothegameisover
  11. breakgameLoop
  12. caseletnewSquarewherenewSquare>finalSquare:
  13. //diceRollwillmoveusbeyondthefinalsquare,sorollagain
  14. continuegameLoop
  15. //thisisavalidmove,sofindoutitseffect
  16. square+=diceRoll
  17. square+=board[square]
  18. println("Gameover!")
如果上述的break语句没有使用标签,那将会中断switch而不是while,使用标签能清晰的表明break想要中断哪个循环 原文链接:https://www.f2er.com/swift/325177.html

猜你在找的Swift相关文章