swift 3.0 字典简单学习

来源:互联网 发布:js杀破狼无损百度云 编辑:程序博客网 时间:2024/06/05 10:23


//1.如何定义字典    //1> 定义不可变字典:使用let修饰    //编译器会根据[]中每一个元素(数组),还是健值队(字典)        //写法一    let dict3 : Dictionary<String, Any> = ["sww": 123,"frg":"911"]        //写法二    let dict2 = ["sww": 123,"frg":"911"] as [String : Any]        //写法三,常用写法    let dict1 : [String: Any] = ["sww": 123,"frg":"911"]    print(dict1,dict2,dict3)//2.如何定义可变字典    //1> 定义可变字典:使用var修饰    //写法一    var dict4 = Dictionary<String,Any>()    //写法二    var dicm5 = [String : Any]()        print(dict4,dicm5)        //2> 对可变字典添加元素    dict4["name"] = "why" //没有oc中的setonjectle    dict4["age"] = 20    dict4["height"] = 1.88    //3》删除元素    dict4.removeValue(forKey:"name")    //4> 修改元素    dict4["name"] = "lmj"    dict4.updateValue("lmj", forKey: "name")    //5>查找元素    //dicm["age"]        //3.遍历    //遍历所有的values    for value in dict4.values    {        print(value)    }    //遍历所有的key    for key in dict4.keys    {        print(key)    }//4.字典合并var dict7 :[String:Any] = ["name":"why", "age":10]let dict8 :[String:Any] = ["height":1.88, "phonenumber":"110"]//let result = dict1 + dict2for (key, value) in dict8 {    dict7[key] = value}print(dict7)


原创粉丝点击