Swift 字典的經常使用方法

        var dict1 = [1:"A",2:"B",3:"C",4:"D",5:"E"];
        var test1 = ["key1":"你好","key2":"Swift","key3":"正在學習","key4":"字典","key5":"取值"]
        //根據鍵去取值
        print(test1["key1"]);
        //字典元素的個數
        print(test1.count);
        //添加字典元素
        dict1[6] = "F";
        test1["key"] = "test";
        //刪除字典中的元素
        test1.removeValue(forKey: "key1");
        //修改字典元素
        test1["key"] = "李平";
        //遍歷
        for (key,value) in test1{
            print("key\(key),value,\(value)");
        }
        for testKey in test1.keys{
            print(testKey);
        }
        for testValue in test1.values{
            print(testValue);
        }
        //把字典裏的鍵或值轉化爲數組
        let textKeyArr = Array(test1.keys);
        print(textKeyArr);
        let textValueArr = Array(test1.values);
        print(textValueArr);數組

相關文章
相關標籤/搜索