在Swift中排序词典 [英] Sort a Dictionary in Swift

查看:98
本文介绍了在Swift中排序词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个话题已经被讨论了,但是我无法解决寻找其他的答案,所以对于我的收获,提前抱歉!

I know that this topic has been already discussed but I can't solve looking other answers, so sorry in advance for my ripetion!

我需要排序字典按键

codeValueDict = ["us": "$", "it": "€", "fr": "€"]

所以我需要一个这样的字典

so I need a dictionary like this

sortedDict = ["fr": "€", "it": "€", "us": "$"]

但我不能这样做。

我尝试过这个

let sortedKeysAndValues = sorted(dictionary) { $0.0 < $1.0 }

但是,当我需要从这个字典(键和值)创建两个数组,并使用该解决方案

but after I need to create two arrays from this dictionary (keys and values) and, using that solution

codesArray = sortedKeysAndValues.keys.array

给我错误'[(String,String)]'没有名为'keys'的成员,因为该解决方案不会完全返回

give me the error '[(String, String)]' does not have a member named 'keys' because that solution doesn't return exactly a dictionary.

所以我尝试了另一个解决方案:

So i tried another solution:

    let prova = codiceNomeDict as NSDictionary
    for (k,v) in (Array(codiceNomeDict).sorted {$0.1 < $1.1}) {
        let value = "[\"\(k)\": \"\(v)\"]"
        println(value)
    }

哪个工作很好,但是我不知道如何创建一个新的值的字典

Which works good but then I don't know how create a new dictionary of values.

什么是最好的解决方案?

What's the best solution? How to make it works?

推荐答案

上面的排序函数的输出是一个数组。所以你不能得到钥匙像字典的值。但是您可以使用 map 函数来检索那些排序的键&值

The output of sorted function above is an Array. So you cannot get keys & values like a Dictionary. But you can use map function to retrieve those sorted keys & values


返回包含 {根据}的排序元素的数组。
排序算法不稳定(可以更改
元素的相对顺序,其中isOrderedBefore不建立顺序)。

Return an Array containing the sorted elements of source{according}. The sorting algorithm is not stable (can change the relative order of elements for which isOrderedBefore does not establish an order).



let codeValueDict = ["us": "$", "it": "€", "fr": "€"]

let sortedArray = sorted(codeValueDict, {$0.0 < $1.0})
print(sortedArray)

let keys = sortedArray.map {return $0.0 }
print(keys)

let values = sortedArray.map {return $0.1 }
print(values)

这篇关于在Swift中排序词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆