Swift 基础学习(字典)
2016-03-03 14:30
344 查看
//(9)字典的概念和定义(key:value) //哈希查找 //addr = hash(key), value = hashTable[addr] //key一定是可hash的,String/Int/Float/Bool都是遵守hash的 var dic = [:] dic = [1:"1", 2:"2"] var dic1 = ["1":"1","2":"2"] var dic2 = ["1":1, "2":2] print(dic) print(dic1) print(dic2) var dic3: Dictionary<String, Int> = ["3":3] var dic4: [String: Int] = ["3":3] print(dic3) print(dic4) print(dic.count) //(10)字典的操作 var dict = ["apple":"苹果", "bag":"包"] print(dict["apple"]) //修改某个值 dict["apple"] = "香蕉" print(dict["apple"]) //更新某个值 dict.updateValue("苹果", forKey: "apple") print(dict) //如果键值对应经在字典中,那么会更新键值对;如果不存在相应的键值对,那么这个键值对会被加到字典中同时返回一个nil //存在的情况 if let orig = dict.updateValue("苹果", forKey: "apple"){ print(dict["apple"]) print("==\(orig)") print(dict) } //不存在的情况,字典中会多出一个键值对 if let orig1 = dict.updateValue("草莓", forKey: "appl"){ print(dict["apple"]) print("==\(orig1)") } print(dict) //添加一个元素 dict["an"] = "一个" print(dict) //删除一个元素,返回一个之前key对应的值 if let old = dict.removeValueForKey("an") { print(old) } print(dict) //删除所有 //dict.removeAll(keepCapacity: true) //(11)字典的遍历 for (key, value) in dict { print("\(key): \(value)") } //打印所有的key for key in dict.keys { print(key) } //打印所有的value for value in dict.values { print(value) }
相关文章推荐
- swift资料收集
- swift: Swift中static和class的使用
- swift 快速奔跑的兔几 本节的内容是:iOS上基于文档的应用程序
- Swift2.0(17)泛型技术
- Swift2.0(17)内存管理ARC
- Swift2.0(16)分类与协议
- Swift2.0(15)类型的补充
- Swift2.0(14)引用类型与数值类型
- Swift2.0(13)构造方法
- Swift2.0(12)继承与多态
- Swift2.0(11)对象基础
- Swift 笔记(十)
- Swift2.0(10)闭包
- Swift2.0(9)函数的使用(二)
- swift函数入门
- Swift2.0(9)函数的使用(一)
- swiftt之表格控件(UITableView)详解,出错,求指南
- 大熊的swift学习笔记(二)
- Swift2.0(8)分支循环
- Swift2.0(7)运算符