[iOS翻訳]『The Swift Programming Language』Control Flow-Controlストリーム
Swiftは、すべてのcクラス言語の制御フロー構造を提供します.forとwhileループを含めて、1つのタスクを複数回実行します.if文とswitch文は、決定された条件下で異なるブランチのコードを実行する.breakキーとcontinueキーは、実行プロセスをコードの別のポイントに移動します.
C言語の伝統的なfor-condition-incrementループに加えて、Swiftはfor-inループを加え、arrays、dictionaries、ranges、stringsなどの他のシーケンスタイプをより容易に遍歴することができます.
Swiftのswitch文もC言語よりずっと強いです.Swiftのswitch文のcase文は次のcaseに「落ちる」ことはなく、c言語がbreak文を書くのを忘れたことによるエラーを回避します.caseは、範囲マッチング、メタグループマッチング、または指定されたタイプに投げつけるなど、多くの異なるモードにマッチングすることができる.マッチング値は1つのcase条件で一時定数または変数にバインドでき、caseのコードブロックで使用でき、複雑なマッチング条件では各caseの条件として表すことができる.
For Loops-Forサイクル
forループは、文のセットを複数回実行するために使用され、Swiftは2つの形式を提供します.
For-In
for-inを使用して、配列の範囲、配列内のアイテム、または文字列内の文字など、集合内のアイテムを巡回します.
次の例では、テーブルの5つの要素を印刷します.
1. for index in 1...5 {
2. println("\(index) times 5 is \(index * 5)")
3. }
4. // 1 times 5 is 5
5. // 2 times 5 is 10
6. // 3 times 5 is 15
7. // 4 times 5 is 20
8. // 5 times 5 is 25
1 5 , (...)。Index (1), 。 , , index 5 。 ,index , println 。 , 。
,index , , , , let 。
NOTE
Index 。 index , index , 。
, :
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
answer *= base
}
println("\(base) to the power of \(power) is \(answer)")
// prints "3 to the power of 10 is 59049"
( ,3 10)。 1, 3, 10 , 0 9。 -- 。 _ ( ) , 。
for-in array :
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
println("Hello, \(name)!")
}
// Hello, Anna!
// Hello, Alex!
// Hello, Brian!
// Hello, Jack!
。 (key,value) , for-in (key, value) , 。 , key animalName , legCount :
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
println("\(animalName)s have \(legCount) legs")
}
// spiders have 8 legs
// ants have 6 legs
// cats have 4 legs
Dictionary 。 Dictionary , 。 Collection Types 。
,for-in Character( ):
for character in "Hello" {
println(character)
}
// H
// e
// l
// l
// o
For-Condition-Increment For- -
for-in ,Swift C for
for var index = 0; index < 3; ++index {
println("index is \(index)")
}
// index is 0
// index is 1
// index is 2
:
for ; ; {
}
, C 。 C ,Swift “ ; ; ” 。
:
- ,initialization expression( ) , 。
- condition expression( )。 false( ), , for (}) 。 (true) , 。
- , increment expression( )。 , 。 2 , 。
:
while {
}
( var index = 0) for 。 index , index:
var index: Int
for index = 0; index < 3; ++index {
println("index is \(index)")
}
// index is 0
// index is 1
// index is 2
println("The loop statements were executed \(index) times")
// prints "The loop statements were executed 3 times"
, index 3, 2。 ++index, index 3, index<3 false, 。
While Loops - While
while false , 。Swift while :
- while
- do-while
while
while , true, false。
while :
while {
}
, Snakes and Ladders ( Chutes and Ladders):
:
- 25 , 25 。
- , , 。
- , 。
- , 。
Int 。 finalSquare , 。 26 0 Int , 25 ( 0 25 ):
-
let finalSquare = 25
var board = Int
-
。 , , :
-
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
-
3 , 11。 ,board[03] +08, 8( 3 11 )。 (+i) (-i) , 10 0 , 。( , )
0, 。 :
var square = 0
var diceRoll = 0
while square < finalSquare {
// roll the dice
if ++diceRoll == 7 { diceRoll = 1 }
// move by the rolled amount
square += diceRoll
if square < board.count {
// if we're still on the board, move up or down for a snake or a ladder
square += board[square]
}
}
println("Game over!")
。 ,diceRoll 0 。 while ,diceRoll (++i) , 。++diceRoll diceRoll 。 7, , 1。 diceRoll 1,2,3,4,5,6,1,2 。
, diceRoll 。 25, 。 , board[square] square board count , square 。
,board[square] board , 。 square 26, board[26], 。
While , 。 25, false, 。
While , , 。
Do-While
While do-while, , false。
do-while :
do {
} while
Snakes and Ladders , do-while while 。finalSquare, board, square, diceRoll :
let finalSquare = 25
var board = Int[](count: finalSquare + 1, 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
var square = 0
var diceRoll = 0
, 。 25, 。 。
, “ 0”。 board[0] 0, :
do {
// move up or down for a snake or ladder
square += board[square]
// roll the dice
if ++diceRoll == 7 { diceRoll = 1 }
// move by the rolled amount
square += diceRoll
} while square < finalSquare
println("Game over!")
, , diceRoll , 。
(while square < finalSquare) , 。do-while while 。 do-while , square ,square += board[square] , 。
Conditional Statements -
, , 。 conditional( ) 。
Swift , if switch 。 , if , Switch , 。
If
,if if 。 if true :
var temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {
println("It's very cold. Consider wearing a scarf.")
}
// prints "It's very cold. Consider wearing a scarf."
32 。 。 , if 。
if , :else clause, if false 。 else :
temperatureInFahrenheit = 40
if temperatureInFahrenheit <= 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."
。 40 , , else 。
if , :
temperatureInFahrenheit = 90
if temperatureInFahrenheit <= 32 {
println("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 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."
if 。 else , 。
else , 。
temperatureInFahrenheit = 72
if temperatureInFahrenheit <= 32 {
println("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
println("It's really warm. Don't forget to wear sunscreen.")
}
, if else 。
Switch
Switch 。 , 。switch if 。
,switch :
switch some value to consider {
case value 1:
respond to value 1
case value 2,
value 3:
respond to value 2 or 3
default:
otherwise, do something else
}
switch case( ) , case 。 ,Swift case , 。
switch exhaustive( ), switch case。 switch case , 。 default , 。
switch ,someCharacter:
let someCharacter: Character = "e"
switch someCharacter {
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"
Switch case 5 。 , case 。
case , switch default 。 switch 。
No Implicit Fallthrough -
C objective-c switch ,Swift ( break) switch case case。 ,switch case , break。 C ,swift switch , case 。
NOTE
, case , :[Break in a Switch Statement]
case 。 , case :
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a":
case "A":
println("The letter A")
default:
println("Not the letter A")
}
// this will report a compile-time error
C Switch, switch "a" "A"。 ,case "a" : 。 case , 。
, , :
switch some value to consider {
case value 1,
value 2:
statements
}
NOTE
switch case , fallthrough ,
Range Matching -
switch case 。 。
let count = 3_000_000_000_000
let countedThings = "stars in the Milky Way"
var naturalCount: String
switch count {
case 0:
naturalCount = "no"
case 1...3:
naturalCount = "a few"
case 4...9:
naturalCount = "several"
case 10...99:
naturalCount = "tens of"
case 100...999:
naturalCount = "hundreds of"
case 1000...999_999:
naturalCount = "thousands of"
default:
naturalCount = "millions and millions of"
}
println("There are \(naturalCount) \(countedThings).")
// prints "There are millions and millions of stars in the Milky Way."
Tuples
switch 。 。 , (_) 。
(x,y), (Int, Int) , :
let somePoint = (1, 1)
switch somePoint {
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"
Switch (0,0) , x , y , 4X4 , 。
C ,Swift switch case 。 (0,0) case。 , , case 。 (0,0) case(0,0), case 。
Value Bindings
switch case , case 。 value binding( ), case “ ”。
(x,y), (Int,Int) , :
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
println("on the x-axis with an x value of \(x)")
case (0, let y):
println("on the y-axis with a y value of \(y)")
case let (x, y):
println("somewhere else at (\(x), \(y))")
}
// prints "on the x-axis with an x value of 2
switch x , y , 。
switch case x y, anotherPoint 。 case ,case (let x, 0), y 0, x x 。 , case,case (0, let y), x 0, y y 。
, case 。 println 。
switch default case。 case,case let (x, y), 。 , , default switch 。
, x y let, case 。 , , var 。 , 。 case 。
Where
switch case where 。 (x,y) :
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
println("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
println("(\(x), \(y)) is on the line x == -y")
case let (x, y):
println("(\(x), \(y)) is just some arbitrary point")
}
// prints "(1, -1) is on the line x == -y"
switch x == y, x == -y, 。
switch case x y, point 。 where , 。 where true,Switch case point 。
, case , default。
Control Transfer Statements -
, 。Swift :
- continue
- break
- fallthrough
- return
control, break fallthrough 。reture Functions 。
Continue
Continue , 。 “ ”, 。
NOTE
for-condition-increment , continue 。 , 。
, :
let puzzleInput = "great minds think alike"
var puzzleOutput = ""
for character in puzzleInput {
switch character {
case "a", "e", "i", "o", "u", " ":
continue
default:
puzzleOutput += character
}
}
println(puzzleOutput)
// prints "grtmndsthnklk"
, , continue 。 , 。 switch ( ) , 。
Break
Break 。 switch 。
Break in a Loop Statement - Break
break, , (}) 。 , 。
Break in a Switch Statement - Switch break
switch break,switch , switch (}) 。
switch ( ) case。 Swift switch , case , case。 switch break ,case break switch。
NOTE
switch case 。 , switch case 。 break case。
switch , 。 switch :
let numberSymbol: Character = " " // Simplified Chinese for the number 3
var possibleIntegerValue: Int?
switch numberSymbol {
case "1", "١", " ", "๑":
possibleIntegerValue = 1
case "2", "٢", " ", "๒":
possibleIntegerValue = 2
case "3", "٣", " ", "๓":
possibleIntegerValue = 3
case "4", "٤", " ", "๔":
possibleIntegerValue = 4
default:
break
}
if let integerValue = 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."
numberSymbol , , 1 4 。 , case Int possibleIntegerValue 。
switch , 。possibleIntegerValue nil, 。 case , possibleIntegerValue 。
, default 。 default , break。 default ,break switch, if let 。
Fallthrough
Swift Switch case case。 , switch case 。 ,C case break 。 C ,Swift switch , case 。
C , fallthrough 。 fallthrough :
let integerToDescribe = 5
var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
description += " a prime number, and also"
fallthrough
default:
description += " an integer."
}
println(description)
// prints "The number 5 is a prime number, and also an integer."
description String 。 switch integerToDescribe 。 integerToDescribe , description , 。 fallthrough “ ”default 。default , switch 。
integerToDescribe , switch case。 case, integerToDescribe default 。
switch , println 。 ,5 。
NOTE
fallthrough case , case。fallthrough case( default) , C 。
Labeled Statements -
switch ,Swift switch 。 , switch break。 , break 。 , ,continue 。
, statement label switch, break continue 。
, “:”。 while , switch 。
while , break continue ,Snakes and Ladders :
- , 25
25 , 25 。
finalSquare, board, square, diceRoll :
let finalSquare = 25
var board = Int[](count: finalSquare + 1, 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
var square = 0
var diceRoll = 0
while switch 。While gameLoop, Snakes and Ladders Game 。
While while square != finalSquare, 25 :
gameLoop: while square != finalSquare {
if ++diceRoll == 7 { diceRoll = 1 }
switch square + diceRoll {
case finalSquare:
// diceRoll will move us to the final square, so the game is over
break gameLoop
case let newSquare where newSquare > finalSquare:
// diceRoll will move us beyond the final square, so roll again
continue gameLoop
default:
// this is a valid move, so find out its effect
square += diceRoll
square += board[square]
}
}
println("Game over!")
。 ,switch , :
- , 。break gameLoop , while 。
- , , 。break gameLoop , 。
-
, 。 。 , while , 。
NOTE break gameLoop , switch , while 。 gameLoop 。
, continue gameLoop gameLoop 。 , 。 , gameLoop 。 break , 。