1. 程式人生 > >swift3.0 字典的基本用法

swift3.0 字典的基本用法

自學swift3.0,如果有什麼錯誤或建議的話歡迎吐槽哦~

        //1.字典的定義使用[key:value,key:value]快速定義
        let dic:[String:Any] = ["name":"張三","age":22]
        print(dic)
        
        //陣列字典
        let arrDic:[[String:Any]] = [
            ["name":"張三","age":22],
            ["name":"李四","age":24]
        ]
        print(arrDic)
        //2.可變字典的增刪改查
        var dictionary:[String:Any] = ["name":"張三","age":22]
        print(dictionary)
        
        /*
         key存在則為修改,key不存在 則為新增
         */
        //增加鍵值對
        dictionary["score"] = 99
        print(dictionary)
        
        //修改鍵值對
        dictionary["age"] = 33
        print(dictionary)
        
        //刪除鍵值對
        // ps: 字典是通過KEY來定位值的,所有的KEY必須是可以 hash/雜湊 的 (md5就是一種雜湊,雜湊就是將字串變成唯一的整數,便於查詢,能夠提高字典遍歷的速度)
//        dictionary.removeValue(forKey: <#T##Hashable#>)
        
        dictionary.removeValue(forKey: "score")
        print(dictionary)
        
        //字典遍歷
        //寫法一
        for e in dictionary {
            print("key = \(e.key)   value = \(e.value)")
            
        }
        
        //寫法二
        for (key,value) in dictionary {
            print("key = \(key)   value = \(value)")
        }
        
        //字典合併
        var dic1 = ["name":"小明","score":"88"]
        print(dic1)
        let dic2 = ["teacher":"老大"]
        
        for (key,value) in dic2 {
            dic1[key] = value
        }
        print(dic1)