我從 API 獲取字典 [String: Int],按值對其進行排序。在那,我得到了一個元組陣列,在那個元組陣列中,我需要將鍵分開,并希望以相同的排序順序使用該鍵創建一個陣列。
我嘗試了一種從該陣列中獲取物件并將其添加到字典中的方法,但它無法正常作業,因為在添加或添加鍵后字典變得無序,需要幫助來解決此問題
試過的代碼
let personalInfoDict = screenConfigResponse?.screenConfiguration?.personalInformation
let personalDict : [String : Int]?
if let dict = personalInfoDict, dict.count > 0 {
personalDict = self.sortWithKeys(dict)
}
func sortWithKeys(_ dict: [String: Int]) -> [String: Int] {
let sorted = dict.sorted(by: { $0.value < $1.value })
var newDict: [String: Int] = [:]
for sortedDict in sorted {
newDict[sortedDict.key] = sortedDict.value
}
return newDict
}
在進行排序時,我得到了正確排序的順序,但是當我回圈并將其添加到 newDict 中時,它是無序的,有沒有辦法只從元組陣列中獲取鍵
uj5u.com熱心網友回復:
也許您可以將其轉換為元組陣列:
let personalInfoDict = screenConfigResponse?.screenConfiguration?.personalInformation
let personalPairs = personalInfoDict
.reduce(into: [(String, Int)]()) { $0.append(($1.key, $1.value)) }
.sorted(by: { $0.0 < $1.0 })
if let pArray = personalPairs, pArray.count > 0 {
for obj in pArray {
personalInformationArray.append(obj.0)
}
}
現在你有一個[(String, Int)]有序陣列
uj5u.com熱心網友回復:
對于文學詞典,有一種哈希表。但是 HashTables不是有序的資料結構,所以你得到的效果是預期的行為。
但是,Apple 提供了一個可選包,可以將其他資料結構添加到您的專案中 ( https://github.com/apple/swift-collections )。特別是我認為“OrderedDictionary”是您的解決方案。
let baseDict : [String:Int] = ["Test1" : 5,
"Test2" : 1,
"Test3" : 4]
let orderedDict : OrderedDictionary<String, Int> = sortWithKeys(baseDict: baseDict)
print(orderedDict)
func sortWithKeys(baseDict : [String:Int]) -> OrderedDictionary<String, Int>
{
let temp = baseDict.sorted(by: { $0.value < $1.value })
var newDict : OrderedDictionary<String, Int> = [:]
for element in temp {
newDict[element.key] = element.value
}
return newDict
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358755.html
上一篇:計算字典的每個值中術語的出現次數
