swift语言学习笔记(4)

来源:互联网 发布:电脑无法访问网络共享 编辑:程序博客网 时间:2024/05/19 16:04
控制流
For-In
循环来遍历一个集合里面的所有元素,例如数字表示的范围、数组中元素和字符串中的字符


for condition increment
注意:condition是每次循环的开始时自动赋值的常量,隐式声明,无需自己声明let。
condition常量只存在于循环的生命周期里。想condition在循环之后的值使用,可以循环之前声明为一个变量;同时,如果不需要范围中每一项,可以用下划线_来代替(condition)来忽略.


//遍历范围
for index in 1...5 {
println(index)
}
//1
//2
//3
//4
//5


//忽略每一项
for _ in 1..4 {
println("fine")
}


//显式声明index (存疑?)
var index = 0,result = 0
for index in 1...3 {
result += index
}
println("\(index) \(result)") //3 6


//遍历字符串
for charResult in "something" {
println(charResult)
}


//遍历数组
let names = ["Anna","Alex","Jack"]
for name in names {
println(name)
}


//遍历字典
let colorNum = ["red":1,"blue":2,"yellow":3]
for (color,num) in colorNum {
println("this color \(color) num is \(num)")
}


switch
不用写break,执行完case语句自动结束switch语句
如果想贯穿case,可以显式case语句中声明fallthrough
let someNum = 0
switch someNum {
case 1,2,3:
//to do
case 4,5 :
//to do
fallthrough
default :
//to do
}


//范围匹配
let count = 1000
swith count {
case 0 :
println("this is nothing")
case 1...100 :
println("hundreds")
case 101...1000 :
println("thousands")
default:
println("this is over")
}


//匹配元组
1、匹配元组中值、范围和下划线(所有值)
let somePoint = (1,1)
switch somePoint {
case (0,0) :
//to do
case (_,0):
//to do
case (-1...1,1...1) :
//to do
default :
//to do
}


//值绑定
let anotherPoint = (2,0)
switch anotherPoint {
case (let x,0) :
println("on the x is \(x)")
case (0,let y) :
println("on the y is \(y)")
case let (x ,y)
//to do
}


where
let yetAnotherPoint = (1,-1)
switch yetAnotherPoint {
case let (x,y) where x == y :
println("x == y")
case let (x,y) where x == -y :
println("x == -y")
case let (x,y) :
//to do
}
0 0