我知道这个话题已经讨论过了,但我无法解决寻找其他答案,所以提前为我的成熟道歉!
我需要按键对这个字典进行排序
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/