继续上篇,
swift的数据字典感觉比较简单,举例说明:
import Foundation
var dir = [0:"dir0",1:"dir1"]
var dir2:Dictionary<Int,String> = [0:"test0",1:"test1"]
dir.removeValueForKey(1);
println(dir[0])
println(dir2[0]);
println(dir);
//循环遍历下
for(k,v) in dir2
{
println("\(k)=\(v)")
}
//获取键
for k in dir2.keys
{
println(dir2[k])
}
////获取值
for v in dir2.values
{
println(dir2[v])
}
var gfDir2=dir2.generate()
for x in 0..gfDir2.count
{
println(gfDir2.next()!.1)
}
dir2.updateValue("test2",forKey:2)
println(dir2)
输出结果:
dir0
test0
dir0
0=test0
1=test1
0
1
test0
test1
test0
test1
[0:"test0",1:"test1",2:"test2"]
swift里提供了值范围运算符:
var curValue :Range<Int>= 0..2(注意,这里提供的范围是0<=x<2)
for x in curValue
{
println(x)
}
输出:
0
1
swift提供了下划线_来进行范围匹配:
import Foundation
var curValue =(0,1,2)
switch curValue
{
case(_,_):
print("right")
default:
print("default")
}
swift提供了值绑定的概念,比较新颖:
var curValue =(0,2)
switch curValue
{
case (let x,2):
println(x)
default:
println("default")
}
输出结果:
0
还有条件匹配:
let curValue=2;
switch curValue
{
case curValue where curValue>0 && curValue<3:
println(curValue)
default:
println("default")
}
输出结果:
2
原文链接:https://www.f2er.com/swift/324434.html