Swift学习之路-字典的定义与使用

Swift学习之路-字典的定义与使用

相比较OC的字典有可变与不可变等的区分,既NSDictionary和NSMutableDictionary
而Swift也有可变和不可变字典,用let和var来区别

定义字典

iOS 中字典是由key和value组成的,字典允许按照某个键来访问元素。key集合不能重复,但是value集合是可重复的

定义一个不可变字典

    //方法一
    let dicA = ["a":12,"b":13]
    print(dicA)
    //方法二
    //如果key-value 的数据类型不一致用以下方法
    let dict = ["name":"张","age":18] as [String : Any]
    print(dict)

上面定义字典省略了Dictionary

    //方法三
let dict:Dictionary = ["a":12,"b":14];
    print(dict)

定义一个可变的字典

var dic:Dictionary = ["name":"张三","age":14]
    print(dic)

往字典里面增加一个元素

    print("-------新增")
    dic["title"] = "大哥"
    print(dic)

字典里面修改一个元素

    print("-------修改")
    dic["name"] = "李四"
    print(dic)

字典里面删除一个元素

    print("-------删除")
    //方法一
    //找到元素所在的位置
    if let index = dic.index(forKey: "age") {
    //删除这个位置对应的元素
        let olditem = dic.remove(at: index)
    }
    print(dic)
    //方法二
    dic.removeValue(forKey: "age")

遍历字典

   let dic:Dictionary = ["name":"张三","age":14,"title":"老板"]
    //遍历元组 let e: (key: String, value: Any)
    for e in dic {
        print("\(e.key) \(e.value)")
    }
    方法二
    print("-------同时遍历key和value")
    for (kkk,vvv) in dic {
        print("\(kkk) \(vvv)")
    }
    //enumerated() 枚举
    print("-------同时遍历key和value和索引")
    for (kkk,vvv) in dic.enumerated() {
        print("\(kkk) \(vvv)")
    }

合并字典

    var dic:Dictionary = ["name":"张三","age":14,"title":"老板"]
    let dict:Dictionary = ["name":"大瓜","height":1.9]
    for dd in dict {
        dic[dd.key] = dict[dd.key]
    }
    print(dic)

你可能感兴趣的:(Swift学习之路-字典的定义与使用)