[swift 进阶]读书笔记-C2P2字典

327 阅读1分钟

第二章:内建集合类型

2.2字典

字典的可变性:


    var dict = ["name":"liaoWorking","age":"17"]

知识点1:书中提到了可以用updateValue(_:forKey:) 获取到更新之前如果有值的旧值。

     /// 得到更新键值对之前的值 updateValue
    let oldValue = dict.updateValue("18", forKey: "age")
    print(oldValue) // Optional("17")
    print(dict["age"]) //Optional("18")

注:这个方法在实际项目中的使用场景还没怎么想到😂 欢迎大家补充场景。 我也是看书之后才发现还有这种操作。

有用的字典方法


字典的合并 merge

 let newDict = ["name":"Jane","age":"19","gender":"M"]
    dict.merge(newDict) { (dictValue, newDictValue) -> String in
        print(dictValue)    // liaoworking 相同key时候的dictValue
        print(newDictValue)     //Jane 相同key时候的newDictValue
        
        return newDictValue //返回你觉得应该选择的value 我这里默认都是newDictValue
    }
    print(dict)["name": "Jane", "age": "19", "gender": "M"]

注:闭包里面的处理是逻辑是当两个dict 有相同的key return出我们觉得合适的value.

字典value的处理 mapValues

    ///字典的map方法
    let mapDict = dict.mapValues { (value) -> String in
        return "new"+value
    }
    print(mapDict)//["name": "newliaoWorking", "age": "new18"]

这里的使用逻辑和数组中的map类似 不赘述。

Hashable 要求


知识点1:字典的本质是哈希表,通过键的hashValue来确定每个键的位置,所以key必须要准守Hashable协议。

文章源文件地址