iOS - Swift Dictionary 字典

前言

public struct Dictionary<Key : Hashable, Value> : CollectionType, DictionaryLiteralConvertible
    public class NSDictionary : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSFastEnumeration
  • 字典用於存儲無序的數據元素值,它能夠存儲任何類型的元素,甚至能夠將數組做爲字典的元素。

一、Dictionary 與 NSDictionary 的相互轉換

  • Dictionary 與 NSDictionary 之間能夠直接相互轉換。Dictionary 轉轉成 NSDictionary 時,數組中的各項元素被轉換爲 AnyObject 類型。NSDictionary 轉換成 Dictionary 時,數組中的各項元素也被轉換爲 AnyObject 類型。
let dictinoary:[String:String] = ["key1":"value1", "key2":"value"]
        
    // Dictionary 轉 NSDictionary
            
        // Dictionary 轉換成 NSDictionary<AnyObject, AnyObject> 型
        let nsDictionary1:NSDictionary = dictinoary
        
        // Dictionary 轉換成 NSDictionary<AnyObject, AnyObject> 型
        let nsDictionary2:NSDictionary = dictinoary as NSDictionary
            
    // NSDictionary 轉 Dictionary
            
        // NSDictionary 轉換成 Dictionary<AnyObject, AnyObject> 型
        let swiftDictionary1:Dictionary = nsDictionary1 as Dictionary
        
        // NSDictionary 轉換成 Dictionary<String, String> 型
        let swiftDictionary2:Dictionary = nsDictionary1 as! [String:String]

二、字典的 建立

// Dictionary 型字典
            
        // 建立字典變量,指定數據類型爲 Int 型
        let dic1 = [String:Int]()
        
        // 建立字典變量,Dictionary<String, Int> 等價於 [String:Int]
        let dic2 = Dictionary<String, Int>()
        
        // 建立字典變量,不指定數據類型
        let dic3:Dictionary = ["key1":1, "key2":2]
        
        // 建立字典變量,指定數據類型爲 Int 型
        let dic4:Dictionary<String, Int> = ["key1":1, "key2":2, "key3":3]
        
        // 建立字典變量,不指定數據類型
        let dic5 = ["key1":1, "key2":2, "key3":3, "key4":4]
        
        // 建立指定數據類型的字典
        let dic6:[String:Int] = ["key1":1, "key2":2, "key3":3, "key4":4]
        
        // 建立指定數據類型的字典
        let dic7:[String:AnyObject] = ["key1":1, "key2":2, "key3":"value3", "key4":4]
            
    // NSDictionary 型字典
            
        let swiftDictionary = ["key1":1, "key2":2, "key3":3, "key4":4]
            
        let nsdic1:NSDictionary = swiftDictionary
        let nsdic2:NSDictionary = swiftDictionary as NSDictionary
            
        let nsdic3:NSDictionary = NSDictionary(dictionary: swiftDictionary)
        let nsdic4:NSDictionary = NSDictionary(dictionary: ["key1":1, "key2":2, "key3":3, "key4":4])
            
        let nsdic5:NSDictionary = NSDictionary(object: "nsdic5", forKey: "key1")
        let nsdic6:NSDictionary = NSDictionary(objects: ["nsdic6", 2], forKeys: ["key1", "key2"])
        let nsdic7:NSDictionary = NSDictionary(dictionaryLiteral: ("key1", "nsdic7"), 
                                                                  ("key2", 2), 
                                                                  ("key3", 3), 
                                                                  ("key4", 4))
        
        // 從 文件 建立字符串
        let nsdic8:NSDictionary? = NSDictionary(contentsOfFile: NSHomeDirectory() + "/Desktop/test.txt")
            
        // 從 Url 建立字符串                            
        let nsdic9:NSDictionary? = NSDictionary(contentsOfURL: NSURL(fileURLWithPath: NSHomeDirectory() + 
                                                                                      "/Desktop/test.txt"))

三、字典元素個數的計算

// Dictionary 或 NSDictionary 型字典
        
    let dic = ["key1":1, "key2":2, "key3":3, "key4":4]
        
    let num:Int = dic.count

四、經過 key 找對應的 value

// Dictionary 型字典
            
        var dic:Dictionary = ["key1":1, "key2":2, "key3":3, "key4":4]
            
        // 獲取字典中指定 key 對應的值
        let value1 = dic["key2"]
            
    // NSDictionary 型字典

        let nsDic:NSDictionary = NSDictionary(dictionary: ["key1":1, "key2":2, "key3":3, "key4":4])
            
        // 獲取字典中指定 key 對應的值
        let value2:AnyObject? = nsDic["key2"]
        
        // 獲取字典中指定 key 對應的值
        let value3:AnyObject? = nsDic.objectForKey("key2")
        
        // 獲取字典中指定 key 對應的值,key 的值不存在時返回指定的字符串
        let value4 = nsDic.objectsForKeys(["key3", "key4", "key5"], notFoundMarker: "not found")

五、經過 value 找對應的 key

// NSDictionary 型字典
            
        let nsDic:NSDictionary = NSDictionary(dictionary: ["key1":1, "key2":3, "key3":3, "key4":4])
            
        let keys:AnyObject = nsDic.allKeysForObject(3)

六、字典中全部 key 的獲取

// Dictionary 型字典
            
        let dic:Dictionary = ["key1":1, "key2":2, "key3":3, "key4":4]
            
        let keys1 = dic.keys
        
    // NSDictionary 型字典
            
        let nsDic:NSDictionary = NSDictionary(dictionary: ["key1":1, "key2":2, "key3":3, "key4":4])
            
        let keys2 = nsDic.allKeys

七、字典中全部 value 的獲取

// Dictionary 型字典
            
        let dic:Dictionary = ["key1":1, "key2":2, "key3":3, "key4":4]
            
        let values1 = dic.values
            
    // NSDictionary 型字典
            
        let nsDic:NSDictionary = NSDictionary(dictionary: ["key1":1, "key2":2, "key3":3, "key4":4])
            
        let values2 = nsDic.allValues

八、字典鍵值對的 追加

// Dictionary 型字典
            
        var dic:Dictionary = ["key1":1, "key2":2, "key3":3, "key4":4]
            
        // key 不存在時,追加鍵值對(key 值爲新增的,若 key 值已存在則爲修改對應的 value 值)
        dic["key5"] = 5
            
    // NSDictionary 型字典
        
        let nsDic:NSMutableDictionary = NSMutableDictionary(dictionary: ["key1":1, "key2":2, "key3":3, "key4":4])
            
        // key 不存在時,追加鍵值對(key 值爲新增的,若 key 值已存在則爲修改對應的 value 值)
        nsDic["key5"] = 5
        
        // 向字典末尾追加一個字典
        nsDic.addEntriesFromDictionary(["key6":6, "key7":7])

九、字典鍵值對的 修改

// Dictionary 型字典
            
        var dic:Dictionary = ["key1":1, "key2":2, "key3":3, "key4":4]
            
        // key 存在時,修改其值
        dic["key4"] = 100
        
        // 修改指定的 key 對應的值
        dic.updateValue(44, forKey: "key4")
            
    // NSDictionary 型字典
        
        let nsDic:NSMutableDictionary = NSMutableDictionary(dictionary: ["key1":1, "key2":2, "key3":3, "key4":4])
            
        // key 存在時,修改其值
        nsDic["key3"] = 33
        
        // 修改指定的 key 對應的值
        nsDic.setObject(100, forKey: "key4")
        
        // 修改整個字典
        nsDic.setDictionary(["key6":6, "key7":7])

十、字典鍵值對的 刪除

// Dictionary 型字典
            
        var dic:Dictionary = ["key1":1, "key2":2, "key3":3, "key4":4]
            
        // 刪除指定 key 對應的值
        dic.removeValueForKey("key2")
        
        // 刪除字典的全部元素
        dic.removeAll(keepCapacity: true)
            
    // NSDictionary 型字典
            
        let nsDic:NSMutableDictionary = NSMutableDictionary(dictionary: ["key1":1, "key2":2, "key3":3, "key4":4])
            
        // 刪除指定 key 對應的值
        nsDic.removeObjectForKey("key2")
        
        // 刪除指定 key 對應的值
        nsDic.removeObjectsForKeys(["key1", "key4"])
        
        // 刪除字典的全部元素
        nsDic.removeAllObjects()

十一、字典遍歷

// NSDictionary 型字典
        
        let nsDic:NSDictionary = NSDictionary(dictionary: ["key1":1, "key2":2, "key3":3, "key4":4])
            
        // for...in 循環
                
            // 遍歷出的爲 key-value 的元組, key 不須要能夠用 _ 替代
            for (_, obj) in nsDic {
                
                print(obj)
            }
                
        // 閉包遍歷
                
            nsDic.enumerateKeysAndObjectsUsingBlock { (key:AnyObject, obj:AnyObject, stop:UnsafeMutablePointer<ObjCBool>) in
             
                print(obj)
            }
                
        // 迭代器遍歷
                
            // key 迭代器
            
                let keyEnu:NSEnumerator = nsDic.keyEnumerator()
                    
                while let key:AnyObject = keyEnu.nextObject() {
                    
                    print(nsDic.objectForKey(key))
                }
                
            // 對象迭代器
            
                let objEnu:NSEnumerator = nsDic.objectEnumerator()
                    
                while let obj:AnyObject = objEnu.nextObject() {
                    
                    print(obj)
                }

十二、字典排序

// NSDictionary 型字典
            
        let nsDic:NSDictionary = NSDictionary(dictionary: ["key1":"value1", "key2":"value2", "key3":"value3", "key4":"value4"])
            
        // 用閉包排序
                
            let keys1 = nsDic.keysSortedByValueUsingComparator { (obj1:AnyObject, obj2:AnyObject) -> NSComparisonResult in
               
                return (obj1 as! String).compare(obj2 as! String)
            }
                
            for key in keys1 {
                print(nsDic.objectForKey(key))
            }
            
        // 用指定的方法排序
                
            let keys2 = nsDic.keysSortedByValueUsingSelector(#selector(NSNumber.compare(_:)))
                
            for key in keys2 {
                print(nsDic.objectForKey(key))
            }
相關文章
相關標籤/搜索