将Dictionary中的key和value键值反转


1年前 781次点击 来自 移动端

标签: Swift

如题:

let dict = ["key1": "v1", "key2": "v2", "key3": "v3"]

反转键值后:

let dict = ["v1": "key1", "v2": "key2", "v3": "key3"]

注意:笔者在此并没有考虑value重复的问题

可使用如下代码:

Dictionary(uniqueKeysWithValues: dict.map {
    key, value in (value, key)
})

以上代码只是提供一种方法,并未考虑代码的鲁壮性,请周知

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1