swift - 在 Swift 中对字典进行排序

标签 swift sorting dictionary

我知道这个话题已经讨论过了,但我无法解决寻找其他答案,所以提前为我的成熟道歉!

我需要按键对这个字典进行排序

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

所以我需要这样的字典

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

但我不能那样做。

我试过了

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

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

codesArray = sortedKeysAndValues.keys.array

给我错误'[(String, String)]' does not have a member named 'keys' 因为该解决方案不完全返回字典。

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

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

效果很好,但我不知道如何创建一个新的字典。

什么是最好的解决方案?如何让它发挥作用?

最佳答案

上面sorted函数的输出是一个数组。所以你不能像字典那样获取键和值。但是您可以使用 map 函数来检索那些排序的键和值

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 - 在 Swift 中对字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30054854/

相关文章:

swift - 通过 layoutIfNeeded 的图像动画停止工作

objective-c - MPMoviePlayer 视频质量与 Youtube 上的原始视频质量不同

php - PHP 中有简单的 usort 吗?

dictionary - 当操作返回 Future 时如何使用 putIfAbsent

java - 我需要用于在 Lucene 中创建索引的原始文件吗?

c++ - 我可以通过整数索引访问 C++ std::map 中的元素吗?

ios - 无法将类型 'Int' 的值转换为预期的参数类型 'UInt32'

ios - 带有未格式化表情符号的 NSAttributedString 结尾

python - 当键更改并且值是更多键值对时,是否可以对键值对的 JSON 对象进行排序。

python - 根据行中间的数据对行进行排序(在 python 中)