Just some notes after reading Apple’s official online guide.
Most code are from the guide, with some modification by me.
Tuple in switch statement is interesting.
===== Full Notes =====
Control Flow
Time to be Awesome - awesome.rb
1
puts"Awesome!"unlesslame
For-In
Sample
12345678
forindexin1...5{println("\(index) times 5 is \(index * 5)")}// 1 times 5 is 5// 2 times 5 is 10// 3 times 5 is 15// 4 times 5 is 20// 5 times 5 is 25
if no need of value from the range
12345678
letbase=3letpower=10varanswer=1for_in1...power{answer*=base}println("\(base) to the power of \(power) is \(answer)")// prints "3 to the power of 10 is 59049"
letnumberOfLegs=["spider":8,"ant":6,"cat":4]for(animalName,legCount)innumberOfLegs{println("\(animalName)s have \(legCount) legs")}// spiders have 8 legs// cats have 4 legs// ants have 6 legs
Use in string
12345678
forcharacterin"Hello"{println(character)}// H// e// l// l// o
For
Sample
123456
forvarindex=0;index<3;++index{println("index is \(index)")}// index is 0// index is 1// index is 2
- Index is only accessible in the loop
123456789
varindex:Intforindex=0;index<3;++index{println("index is \(index)")}// index is 0// index is 1// index is 2println("The loop statements were executed \(index) times")// prints "The loop statements were executed 3 times"
While Loops
Snakes and Ladders
12345678910111213141516171819
letfinalSquare=25varboard=[Int](count:finalSquare+1,repeatedValue:0)board[03]=+08;board[06]=+11;board[09]=+09;board[10]=+02board[14]=-10;board[19]=-11;board[22]=-02;board[24]=-08varsquare=0vardiceRoll=0whilesquare<finalSquare{// roll the diceif++diceRoll==7{diceRoll=1}// move by the rolled amountsquare+=diceRollifsquare<board.count{// if we're still on the board, move up or down for a snake or a laddersquare+=board[square]}}println("Game over!")
Do-While
Snakes and Ladders
12345678910111213141516
letfinalSquare=25varboard=[Int](count:finalSquare+1,repeatedValue:0)board[03]=+08;board[06]=+11;board[09]=+09;board[10]=+02board[14]=-10;board[19]=-11;board[22]=-02;board[24]=-08varsquare=0vardiceRoll=0do{// move up or down for a snake or laddersquare+=board[square]// roll the diceif++diceRoll==7{diceRoll=1}// move by the rolled amountsquare+=diceRoll}whilesquare<finalSquareprintln("Game over!")
vartemperatureInFahrenheit=30iftemperatureInFahrenheit<=32{println("It's very cold. Consider wearing a scarf.")}// prints "It's very cold. Consider wearing a scarf."temperatureInFahrenheit=40iftemperatureInFahrenheit<=32{println("It's very cold. Consider wearing a scarf.")}else{println("It's not that cold. Wear a t-shirt.")}// prints "It's not that cold. Wear a t-shirt."temperatureInFahrenheit=90iftemperatureInFahrenheit<=32{println("It's very cold. Consider wearing a scarf.")}elseiftemperatureInFahrenheit>=86{println("It's really warm. Don't forget to wear sunscreen.")}else{println("It's not that cold. Wear a t-shirt.")}// prints "It's really warm. Don't forget to wear sunscreen."temperatureInFahrenheit=72iftemperatureInFahrenheit<=32{println("It's very cold. Consider wearing a scarf.")}elseiftemperatureInFahrenheit>=86{println("It's really warm. Don't forget to wear sunscreen.")}
letsomeCharacter:Character="e"switchsomeCharacter{case"a","e","i","o","u":println("\(someCharacter) is a vowel")case"b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z":println("\(someCharacter) is a consonant")default:println("\(someCharacter) is not a vowel or a consonant")}// prints "e is a vowel"
- No Implicit Fallthrough
In contrast with switch statements in C and Objective-C, switch statements in Swift do not fall through the bottom of each case and into the next one by default. Instead, the entire switch statement finishes its execution as soon as the first matching switch case is completed, without requiring an explicit break statement. This makes the switch statement safer and easier to use than in C, and avoids executing more than one switch case by mistake.
- Bad case
123456789
letanotherCharacter:Character="a"switchanotherCharacter{case"a":// Each case must contain at least one executable statement.case"A":println("The letter A")default:println("Not the letter A")}// this will report a compile-time error
- Range Matching
12345678910111213141516171819
letcount=3_000_000_000_000letcountedThings="stars in the Milky Way"varnaturalCount:Stringswitchcount{case0:naturalCount="no"case1...3:naturalCount="a few"case4...9:naturalCount="several"case10...99:naturalCount="tens of"case100...999:naturalCount="hundreds of"case1000...999_999:naturalCount="thousands of"default:naturalCount="millions and millions of"}
- Tuple
1234567891011121314
letsomePoint=(1,1)switchsomePoint{case(0,0):println("(0, 0) is at the origin")case(_,0):println("(\(somePoint.0), 0) is on the x-axis")case(0,_):println("(0, \(somePoint.1)) is on the y-axis")case(-2...2,-2...2):println("(\(somePoint.0), \(somePoint.1)) is inside the box")default:println("(\(somePoint.0), \(somePoint.1)) is outside of the box")}// prints "(1, 1) is inside the box"
- Value Bindings
12345678910
letanotherPoint=(2,0)switchanotherPoint{case(letx,0):println("on the x-axis with an x value of \(x)")case(0,lety):println("on the y-axis with a y value of \(y)")caselet(x,y):println("somewhere else at (\(x), \(y))")}// prints "on the x-axis with an x value of 2"
- Where
12345678910
letyetAnotherPoint=(1,-1)switchyetAnotherPoint{caselet(x,y)wherex==y:println("(\(x), \(y)) is on the line x == y")caselet(x,y)wherex==-y:println("(\(x), \(y)) is on the line x == -y")caselet(x,y):println("(\(x), \(y)) is just some arbitrary point")}// prints "(1, -1) is on the line x == -y"
Control Transfer Statements
Continue
The continue statement tells a loop to stop what it is doing and start again at the beginning of the next iteration through the loop. It says “I am done with the current loop iteration” without leaving the loop altogether.
123456789101112
letpuzzleInput="great minds think alike"varpuzzleOutput=""forcharacterinpuzzleInput{switchcharacter{case"a","e","i","o","u"," ":continuedefault:puzzleOutput.append(character)}}println(puzzleOutput)// prints "grtmndsthnklk"
- Break
1234567891011121314151617181920
letnumberSymbol:Character="三"// Simplified Chinese for the number 3varpossibleIntegerValue:Int?switchnumberSymbol{case"1","١","一","๑":possibleIntegerValue=1case"2","٢","二","๒":possibleIntegerValue=2case"3","٣","三","๓":possibleIntegerValue=3case"4","٤","四","๔":possibleIntegerValue=4default:break}ifletintegerValue=possibleIntegerValue{println("The integer value of \(numberSymbol) is \(integerValue).")}else{println("An integer value could not be found for \(numberSymbol).")}// prints "The integer value of 三 is 3."
- Explicit Fallthrough
The fallthrough keyword does not check the case conditions for the switch case that it causes execution to fall into. The fallthrough keyword simply causes code execution to move directly to the statements inside the next case (or default case) block, as in C’s standard switch statement behavior.
1234567891011
letintegerToDescribe=5vardescription="The number \(integerToDescribe) is"switchintegerToDescribe{case2,3,5,7,11,13,17,19:description+=" a prime number, and also"fallthroughdefault:description+=" an integer."}println(description)// prints "The number 5 is a prime number, and also an integer."
- Labeled Statements
12345678910111213141516
gameLoop:whilesquare!=finalSquare{if++diceRoll==7{diceRoll=1}switchsquare+diceRoll{casefinalSquare:// diceRoll will move us to the final square, so the game is overbreakgameLoopcaseletnewSquarewherenewSquare>finalSquare:// diceRoll will move us beyond the final square, so roll againcontinuegameLoopdefault:// this is a valid move, so find out its effectsquare+=diceRollsquare+=board[square]}}println("Game over!")