学习来自《极客学院:Swift中的字典》
工具:Xcode6.4
直接上基础的示例代码,多敲多体会就会有收获:百看不如一敲,一敲就会
1 import Foundation 2 3 //字典的声明 4 var dic1: Dictionary <String,String> 5 var scores: [String:Int] 6 //然后是创建字典 7 dic1 = Dictionary<String,String>() 8 scores = Dictionary<String,Int>(minimumCapacity: 5) 9 10 var emptyDic: [String : Double] = [:]//空字典 11 println(emptyDic.isEmpty) 12 13 //通过常量和变量决定字典是否可变 14 var person = [ "age":18, 15 "name":"heyang", 16 "身高":178] 17 println(person["age"]!) 18 println(person["weight"])//不存在的key,返回为nil 19 person["name"] = "HeYang" 20 println(person["name"]!) 21 22 person["weight"] = 90 23 println("字典是无序的:\(person)")//对不存在的key设置value,字典将会添加key-value对 24 25 //var height: Int? = person["身高"]会报错,原因是person的元素都是NSObject所以上面的字典person是不严谨的 26 var person_1 = ["age":"18", 27 "name":"heyang", 28 "身高":"178"] 29 var height_1: String? = person_1["身高"] 30 if height_1 != nil { 31 println(height_1!) 32 } 33 //updateValue(value: Value, forKey: Key) 34 if let oldName = person_1.updateValue("180", forKey: "身高"){ 35 println("原来的值是:\(oldName)") 36 } 37 println("现在的值是:"+person_1["身高"]!) 38 39 print("遍历:") 40 for (key,value) in person_1{ 41 print("\(key) : \(value) ") 42 } 43 44 println() 45 //字典删除的方法 46 person.removeAll(keepCapacity: false) 47 person_1.removeValueForKey("身高") 48 println("删除之后person:\(person) 和 person_1:\(person_1)") 49 50 //取出字典当中的键值对 51 let keysArr = [String](person_1.keys) 52 let valuesArr = [String](person_1.values) 53 println("keysArr: \(keysArr)") 54 println("valuesArr: \(valuesArr)")
运行输出结果:
时间: 2024-10-15 13:49:44