Swift开发

Swift 字典

2017-11-15  本文已影响9人  追逐_chase
Swift.png
字典的简单介绍
字典的初始化
//创建一个不可变的字典
let  dic = ["a":1,"b":2,"c":3];

//创建一个可变的字典
var countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"];
//字典的声明, []代表类型 String代表key, Any是任意的一个值 value
var dict :[String:Any];
//赋值
dict = ["name" : "why", "age" : 18]

//初始化一个字典 []代表类型 String代表key, Any是任意的一个值 value
var dic1:[String:Any] = Dictionary.init();
//添加元素
dic1["a"] = 1;
//打印结果: ["a": 1]
字典的基本操作,曾,删,改,查
//添加
//初始化字典
var dic1:[String:Any] = Dictionary.init();
dic1["name"] = "cc";
print(dic1);
//更新里面的数据
// updateValue(<#T##value: Any##Any#>, forKey: <#T##String#>)
//第一个参数对应的是 值 Value 第二个参数是:key键值
dic1.updateValue(18, forKey: "age");

//删除
dic1.removeValue(forKey: "name");

//根据哈希索引值 删除

//哈希索引值
let index = dic1.index(forKey: "age");
dic1.remove(at: index!);

字典的遍历
var countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"];

     print(countryCodes)
     // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"

    for k in countryCodes.keys {
        print(k)
     }
    // Prints "BR"
    // Prints "GH"


//遍历
for item in dic {
    print(item);
}
//打印结果呢:
(key: "JP", value: "Japan")
(key: "BR", value: "Brazil")
(key: "GH", value: "Ghana")


for (key,value) in dic {
    
    print("\(key):\(value)");
}

//打印结果:
JP:Japan
BR:Brazil
GH:Ghana

上一篇下一篇

猜你喜欢

热点阅读