1、for循环
//forin写法
for i in -99 ... 99 {
i*i
}
var result = 1
var base = 2
var power = 10
for _ in 1...power {//_忽略值
result *= base
}
- for var i = 0; i < 99 ;i++ 这种传统C语言的for循环写法在swift3.0中被废弃被for_in代替
2、while循环
var aWin = 0
var bWin = 0
var game = 0
while aWin < 3 && bWin < 3{
game += 1
let a = arc4random_uniform(6)+1
let b = arc4random_uniform(6)+1
print("a is \(a) , b is \(b). ",terminator:"")
if a > b{
print("A win!")
bWin = 0
aWin += 1
}
else if a < b{
print("B win!")
aWin = 0
bWin += 1
}
else{
print("draw")
aWin = 0
bWin = 0
}
}
//print(game)
let winner = aWin == 3 ? "A" : "B"
print("After \(game) games, \( winner ) win!")
3、repeat-while循环
swift中do-while循环更改为repeat-while循环,适合至少执行一次循环体的循环
var aWin = false
var bWin = false
repeat{
let a = arc4random_uniform(6)+1
let b = arc4random_uniform(6)+1
print("a is \(a) , b is \(b). ",terminator:"")
if a > b{
aWin = true
}
else if a < b{
bWin = true
}
else{
print("draw",terminator:"")
}
print("")
}while !aWin && !bWin
//print(game)
let winner = aWin ? "A" : "B"
print("\( winner ) win!")
4、continue break控制转移
var a: Int
var b: Int
while true{
let a = arc4random_uniform(6)+1
let b = arc4random_uniform(6)+1
if a == b{
print("draw")
continue
}
let winner = a > b ? "A" : "B"
print("\( winner ) win!")
break
}