swift 基础学习(5) - 字典

前端之家收集整理的这篇文章主要介绍了swift 基础学习(5) - 字典前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
// MARK: - 字典的定义
    func demo4(type: String) -> () {
        // 需要指出字典 键值对的 类型
        let dic1: [String: Any] = ["name": "张三","age": 10]
        let dic2: [String: Any] = ["name": "李四","age": 12]
        
        let array = [dic1,dic2]
        print(array)
    }
//MARK: - 可变字典的增删改
    func demo5(type: String) -> () {
        var dic: [String: Any] = ["name": "王二","age":13]
        
        // 添加修改,都是通过key值取值,key值存在就是修改,不存在就是添加
        
        // 添加键值对
        dic["sex"] = "女"
        
        //修改键值对
        dic["name"] = "麻子"
        print(dic)
        
        // 删除
        dic.removeValue(forKey: "sex")
        print(dic)
    }
//MARK: - 字典的遍历
    func demo6(type: String) -> () {
        let dic: [String: Any] = ["name": "张三","age": 10,"sex": "妖"]
        
        // 元组遍历
        for object in dic {
            print("\(object.key)----\(object.value)")
        }
        for (key,value) in dic {
            print("\(key)-\(value)")
        }
    }
// MARK: - 字典的合并
    func demo7(type: String) -> () {
        var dic: [String: Any] = ["name": "张三","age": 10]
        let dic1: [String : Any] = ["sex": "妖","heigth": 17.0]
        
        for object in dic1 {
            // 取到 dic1 的key 值
            let key = object.key
            // 添加到 dic 中
            dic[key] = object.value
        }
        print(dic)
    }
原文链接:https://www.f2er.com/swift/321847.html

猜你在找的Swift相关文章