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);

详细代码查看:https://github.com/xiaolitou-ping/Swift-All