Dictionary Programming Guide

来源:互联网 发布:八匹马网络加速器 编辑:程序博客网 时间:2024/06/08 01:57

在Swift中,Dictationary是管理键值对的对象。在Dictionary中,key是唯一的,value可以是相同的元素,并且Dictionary中的数据是无序的。Dictationary的内部结构图如下所示:

Dictionary


初始化

// MARK: 初始化private func testInit() {    // 空字典    var dict = [String:String]()    dict = [:]    dict = Dictionary()    dict = Dictionary<String, String>()    // 有元素的字典    dict = ["name":"阳君", "qq":"937447974"]    dict = Dictionary(dictionaryLiteral: ("name","阳君"), ("qq","937447974"))    print("\(dict)")}

 

相关属性

// MARK: 相关属性private func testProperties() {    let dict = ["name":"阳君", "qq":"937447974"]    print("count:\(dict.count)") // 有多个对元素    print("isEmpty:\(dict.isEmpty)") // 是否为空    // 获取所有key    let keys = [String](dict.keys)    print("keys:\(keys)")    // 获取所有value    let values = [String](dict.values)    print("values:\(values)")    print("startIndex:\(dict.startIndex)") // 首脚标    print("endIndex:\(dict.endIndex)")     // 尾脚标}

 

查找元素

// MARK: 查找元素private func testFindingObjects() {    let dict = ["name":"阳君", "qq":"937447974"]    if let dictIndex = dict.indexForKey("name") { // 获取位置        let item = dict[dictIndex] // 根据位置获取键值对        print("key:\(item.0);value:\(item.1)")    }    let value = dict["name"] // 根据key提取Value    print("value:\(value)")    // 遍历输出    for (key, value) in dict {        print("\(key): \(value)")    }    // 所有key输出    for key in dict.keys {        print("key:\(key)")    }    // 所有value输出    for value in dict.values {        print("value: \(value)")    }}

 

增加元素

// MARK: 增加元素private func testAdd() {    var dict = ["name":"阳君", "qq":"937447974"]    // 如果没有则添加,有则修改    dict["language"] = "swift"}

 

删除元素

// MARK: 删除元素private func testRemove() {    var dict = ["name":"阳君", "qq":"937447974"]    let oldValue = dict.removeValueForKey("name")// 根据key删除,并返回删除的value    print("\(oldValue)")    // 先找到位置,然后根据位置删除    if let dictIndex = dict.indexForKey("qq") {        let oldItem = dict.removeAtIndex(dictIndex)// 返回删除的元素对        print("key:\(oldItem.0);value:\(oldItem.1)")    }    dict.removeAll() // 删除所有元素}

 

修改元素

// MARK: 修改元素private func testReplace() {    var dict = ["name":"阳君", "qq":"937447974"]    // 如果没有则添加,有则修改    dict["name"] = "YangJun" // 修改    let oldValue = dict.updateValue("YangJun", forKey: "name") // 修改,并返回原来的value    print("\(oldValue)")}

 

排序

// MARK: 排序private func testSort() {    let dict = ["name":"阳君", "qq":"937447974", "a":"1", "b":"1"]    // 排序主要只排序key或者value,然后借用Array的排序    // 排序key    var array = dict.keys.sort({ str1,str2 in str1 < str2 })     array = dict.keys.sort(<)    // 排序value    array = dict.values.sort({$0 > $1})    print("\(array)")}

 

文件读和写

// MARK: - 文件读和写private func testReadingAndWriting() {    // Document目录    let documents:[String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)    let docDirPath = documents.first!    let path = (docDirPath as NSString).stringByAppendingPathComponent("test.plist")    let url = NSURL(fileURLWithPath: path)    var dict = ["name":"阳君", "qq":"937447974"]    // 写    (dict as NSDictionary).writeToFile(path, atomically: true)    (dict as NSDictionary).writeToURL(url, atomically: true)    // 读    dict = NSDictionary(contentsOfFile: path) as! Dictionary    dict = NSDictionary(contentsOfURL: url) as! Dictionary}

 


其他

参考资料

Dictionary Structure Reference
The Swift Programming Language (Swift 2.1)
NSDictionary Class Reference

 

文档修改记录

时间 描述 2015-10-26 根据Swift2.1 NSDictionary的API总结

 


版权所有:http://blog.csdn.net/y550918116j

0 0
原创粉丝点击