Swift4.0 Dictionary使用詳解


  字典是一種存儲相同類型多重數據的存儲器。每個值(value)都關聯獨特的鍵(key),鍵作為字典中的這個值數據的標識符。和數組中的數據項不同,字典中的數據項並沒有具體順序。我們在需要通過標識符(鍵)訪問數據的時候使用字典。

字典必須滿足的條件:

 (1)字典鍵值對的鍵和值的類型必須明確,可以直接指定,也可以類似數組直接賦值由編譯器自動識別(在自動識別時字典里的類型必須是同一種類型)

 (2)字典必須要初始化

 (3)鍵的類型基本數據類型和遵循哈希(Hashable)協議的類

 

1、初始化一個空字典

//        //初始化一個空字典
        var dict1:Dictionary<Int,String> = [:]//其中鍵是Int型  值是String型
        var dict2:[String:String] = [:]//其中鍵、值都是String型
        var dict3 = [String:String]()
        var dict4 = Dictionary<String,String>()

 

2、字典的增、刪、改、查

//        //增、刪、改、查
        //其中as后的[String : Any]是字典的 鍵、值類型
        var dict = ["name":"sunfusheng", "age":20, "blog":"sunfusheng.com"] as [String : Any]
//       1、增、改  
//        有則更新鍵值對的值,無則增加一個鍵值對
        dict["height"] = 60
        print("dict = \(dict) one = \(String(describing: dict["age"]))")
        
        /**
         打印結果為:dict = ["name": "sunfusheng", "age": 20, "height": 60, "blog": "sunfusheng.com"] one = Optional(20)
         */
        
        // updateValue: 有則更新鍵值對的值,無則增加一個鍵值對,如果字典里含有updateValue的Key那就返回老大值,否則返回nil(nil在Swift中,nil不是指針,它是一個確定的值,用於表示值缺失。任何類型的可選狀態都可以設置為nil,不只是對象類型)
        dict.updateValue("sina", forKey: "weiBo")
        let backValue = dict.updateValue(28, forKey: "age")
        
        
//       2、 查
        /**
         這里的:!強制對Optional值進行拆包
         在Swift中,!和 ?都是拆包但他兩的使用場景不一樣
         !的使用場景:
         1)強制對Optional值進行拆包
         2)聲明隱式拆包變量,一般用於類中的屬性
         
         ?的使用場景:
         1)聲明Optional值變量
         2)在對Optional值操作中,用來判斷是否能響應后面的操作
         */
        let age:Any = dict["age"] as! Int
        
        print("dict = \(dict) \n backValue = \(String(describing: backValue)) \n age = \(age)")
        
        /**
         打印結果為:
         dict = ["name": "sunfusheng", "age": 28, "height": 60, "weiBo": "sina", "blog": "sunfusheng.com"]
         backValue = Optional(20)
         age = 28
         
         */
        
//        3、刪
       
//        (1)可以使用下標語法來通過給某個鍵的對應值 賦值 為 “nil” 來從字典里 移除一個鍵值對
        dict["height"] = nil
        print("nowDic = \(dict)")
       /**
         打印結果為:
         nowDic = ["name": "sunfusheng", "age": 28, "weiBo": "sina", "blog": "sunfusheng.com"]
         字典里的 "height": 60 已經被移除
         */
        
        /**
         (2)通過removeValue(forKey:)這個方法也可以移除鍵值對,這個方法在鍵值對存在的情況下會移除該鍵值對並返回被移除的值(在沒有值的情況下返回nil)
         */
        let removeValure = dict.removeValue(forKey: "name")
        print("dict = \(dict) \n removeValure = \(String(describing: removeValure))")
        /**
         打印結果為:
         dict = ["age": 28, "weiBo": "sina", "blog": "sunfusheng.com"]
         removeValure = Optional("sunfusheng")
         
         有結果可以得:字典里的 "name": "sunfusheng" 已經被移除
         */
        
//        (3)removeAll() 清空字典的所有鍵值對
        dict.removeAll()
        

 

3、判斷字典是否為空

 let dict1:Dictionary<Int,String> = [:]//其中鍵是Int型  值是String型
        let dict = ["name":"sunfusheng", "age":20, "blog":"sunfusheng.com"] as [String : Any]
        
//        1、通過isEmpty判斷
        if dict1.isEmpty {
            print("dict1 字典為空")
        } else {
            print("dict1 不為空 = \(dict1)")
        }
        
        if dict.isEmpty {
            print("dict 字典為空")
        } else {
            print("dict 不為空 = \(dict)")
        }
        /**
         打印結果:
         dict1 字典為空
         dict 不為空 = ["name": "sunfusheng", "age": 20, "blog": "sunfusheng.com"]
         */
        
//        2、通過字典的key的數組來判斷
        let keys1 = dict1.keys.count
        let keys = dict.keys.count
        if keys1 == 0 {
            print("dict1 字典為空")
        } else {
            print("dict1 不為空 = \(dict1)")
        }
        
        if keys == 0 {
            print("dict 字典為空")
        } else {
            print("dict 不為空 = \(dict)")
        }
        /**
         打印結果:
         dict1 字典為空
         dict 不為空 = ["name": "sunfusheng", "age": 20, "blog": "sunfusheng.com"]
         
         兩次結果一樣
         */

 

4、遍歷字典

let dict = ["name":"sunfusheng", "age":20, "blog":"sunfusheng.com"] as [String : Any]
        //字典的遍歷,使用for - in 循環來遍歷字典中的鍵值對,每個字典中的數據項都以(key,value)元組的形式返回,可以使用臨時常量或者變量來分解這些元組
        for dictValure in dict {
             print("字典遍歷的結果:\(dictValure)")
        }
        /**
         輸出結果:
         字典遍歷的結果:(key: "name", value: "sunfusheng")
         字典遍歷的結果:(key: "age", value: 20)
         字典遍歷的結果:(key: "blog", value: "sunfusheng.com")
         */
        
        
        //可以單獨遍歷出字典里的所有keys 或 values值
//        (1)獲取字典中所有的鍵
        for dictKey in dict.keys {
            print("dictKey = \(dictKey)")
        }
        /**
         輸出結果:
         dictKey = name
         dictKey = age
         dictKey = blog
         */
//        (2)獲取字典中的所有值
        for dictValue in dict.values {
            print("dictValue = \(dictValue)")
        }
        /**
         輸出結果:
         dictValue = sunfusheng
         dictValue = 20
         dictValue = sunfusheng.com
         */
        
        //當只是需要使用某個字典的鍵集合或者值集合來作為某個接收Array 可以直接使用keys或者values屬性構造一個新數組
        let dictKeyArray = [String](dict.keys)
        let dictValuesArray = [Any](dict.values)
        print("dictKeyArray = \(dictKeyArray) \n dictValuesArray = \(dictValuesArray)")
        /**
         輸出結果:
         dictKeyArray = ["name", "age", "blog"]
         dictValuesArray = ["sunfusheng", 20, "sunfusheng.com"]
         */

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM