学习来自《极客学院:Swift中的字典》

工具:Xcode6.4

直接上基础的示例代码,多敲多体会就会有收获:百看不如一敲,一敲就会

 import Foundation

 //字典的声明
var dic1: Dictionary <String,String>
var scores: [String:Int]
//然后是创建字典
dic1 = Dictionary<String,String>()
scores = Dictionary<String,Int>(minimumCapacity: ) var emptyDic: [String : Double] = [:]//空字典
println(emptyDic.isEmpty) //通过常量和变量决定字典是否可变
var person = [ "age":,
"name":"heyang",
"身高":]
println(person["age"]!)
println(person["weight"])//不存在的key,返回为nil
person["name"] = "HeYang"
println(person["name"]!) person["weight"] =
println("字典是无序的:\(person)")//对不存在的key设置value,字典将会添加key-value对 //var height: Int? = person["身高"]会报错,原因是person的元素都是NSObject所以上面的字典person是不严谨的
var person_1 = ["age":"",
"name":"heyang",
"身高":""]
var height_1: String? = person_1["身高"]
if height_1 != nil {
println(height_1!)
}
//updateValue(value: Value, forKey: Key)
if let oldName = person_1.updateValue("", forKey: "身高"){
println("原来的值是:\(oldName)")
}
println("现在的值是:"+person_1["身高"]!) print("遍历:")
for (key,value) in person_1{
print("\(key) : \(value) ")
} println()
//字典删除的方法
person.removeAll(keepCapacity: false)
person_1.removeValueForKey("身高")
println("删除之后person:\(person) 和 person_1:\(person_1)") //取出字典当中的键值对
let keysArr = [String](person_1.keys)
let valuesArr = [String](person_1.values)
println("keysArr: \(keysArr)")
println("valuesArr: \(valuesArr)")

运行输出结果:

Swift中的字典-LMLPHP

05-01 03:21