l For in 遍历集合中元素
for index in1...5 {
print("\(index)times 5 is \(index * 5)")
}
如果你不需要知道区间内每一项的值,你可以使用下划线(_)替代变量名来忽略对值的访问:
let base = 3
let power = 10
var answer = 1
for _ in1...power {
answer *= base
}
print("\(base)to the power of \(power) is \(answer)")
// 输出 "3 tothe power of 10 is 59049"
l For 循环
格式定义如下:
for initialization; condition; increment { statements }
//index只在循序体内有效,如果要在外部访问则需要在外部声明。
for var index = 0; index < 3;++index
{
print("index is\(index)")
}
// index is 0
// index is 1
// index is 2
l while循环
格式定义如下:
while condition{ statement }
var st = 3
while st < 1
{
Print(“st:\(st)”)
st --
}
l Repeat-While(类似do-while) 循环
格式定义如下:
repeat { statements }while condition
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
repeat {
// 顺着梯子爬上去或者顺着蛇滑下去
square += board[square]
// 掷骰子 if ++diceRoll== 7 { diceRoll = 1 }
// 根据点数移动
square += diceRoll
} while square < finalSquare
print("Game over!")
l if语句
var temperatureInFahrenheit = 30
if temperatureInFahrenheit <=32
{
print("It's very cold. Consider wearing ascarf.")
}
//---------------
If .. {
}else if .. {
}else {
}
l 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特点:
a) 不存在隐式的贯穿(No Implicit Fallthrough)
Swift 中