for循环
<span style="font-size:18px;">
//1.swift提供了可以以区间的形式遍历的方法
for item in 1...5 {
println(item)
}
//2.闪光点 : 你可以使用下划线(_)替代变量名来忽略对值的访问
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
answer *= base
}
println("\(base) to the power of \(power) is \(answer)")
// 输出 "3 to the power of 10 is 59049"
//3.遍历字典
var dict = ["key1" : 1 ,"key2" : 2,"key3" : 3]
for (key1 ,value1) in dict {
println(key1+"\(value1)")
}
//4.遍历字符串
for char in "hello" {
println(char)
}
//5.在初始化表达式中声明的常量和变量(比如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")
// 输出 "The loop statements were executed 3 times
</span>
<span style="font-size:18px;">
//1.switch 可以case 多个条件
var intNum = 1
switch intNum {
case 1,3,5,7,9 :
println("1")
println("123")
case 2,4,6,8,10 :
println("2")
default:
println("other")
}
//2.switch 可以判断区间
var intNum2 = 201
switch intNum2 {
case 1...200 :
println("<200")
case 201...500:
println("200< && <500")
default :
println("other")
}
//3.switch 判断元组,用作point的判断太合适了!!!
var point = (x : 110,y : 99)
switch point {
case (0..100 , 0..100 ):
println("左上角")
case (220..320 , 0..100 ) :
println("右上角")
case (0..100 , 380..480) :
println("左下角")
case (220..320 , 380..480) :
println("右下角")
case (_,_) :// _ 可以代表所有值
println("中间")
default :
println("error")
}
//4.可以绑定值
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))")
}
// 输出 "on the x-axis with an x value of 2"
</span>
<span style="font-size:18px;">//5.switch 判断元组 , 用where 做判断条件
var point1 = (10,99)
switch point1 {
case let (x, y) where x < 100 && y < 100:
println("左上角")
case let (x, y) where 220 < x && x < 320 && y < 100:
println("右上角")
case let (x, y) where x < 100 && y < 480 && y > 380:
println("左下角")
case let (x, y) where 200 < x && x < 100 && y < 480 && y > 380:
println("右下角")
case (_,_) :// _ 可以代表所有值
println("中间")
default :
println("error")
</span>
<span style="font-size:18px;">
//6. 使用贯穿来进入下一个case
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)
// 输出 "The number 5 is a prime number, and also an integer."</span>
<span style="font-size:18px;">//7 . 标签
gameLoop: while square != finalSquare {
if ++diceRoll == 7 { diceRoll = 1 }
switch square + diceRoll {
case finalSquare:
// 到达最后一个方块,游戏结束
break gameLoop
case let newSquare where newSquare > finalSquare:
// 超出最后一个方块,再掷一次骰子
continue gameLoop
default:
// 本次移动有效
square += diceRoll
square += board[square]
}
}
println("Game over!")</span>