加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift 3.0 字典简单学习

发布时间:2020-12-14 06:12:24 所属栏目:百科 来源:网络整理
导读://1.如何定义字典 //1 定义不可变字典:使用let修饰 //编译器会根据[]中每一个元素(数组),还是健值队(字典) //写法一 let dict3 : DictionaryString,Any = ["sww": 123,"frg":"911"] //写法二 let dict2 = ["sww": 123,"frg":"911"] as [String : Any]


//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 + dict2
for (key,value) in dict8 {
    dict7[key] = value
}

print(dict7)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读