[英]Sorting through Dictionaries of array in swift
感謝您花時間查看問題。
我正在嘗試按降序對 Arrays 的字典進行排序,請參閱下面的數據 model。 我不能在這個數組上使用任何排序方法,因為字典嵌套在另一個數組中。
var data = [[22 : [24 : 2, 35 : 3]], [21 : [24 : 21, 72 : 26 ]], [23 : [43 : 24, 53 : 12]]]
排序方法無法識別字典,因為它們是嵌套的。 有什么想法嗎?
var sortedKeysAndValues = Array(data.keys).sorted(<)
這會引發錯誤:'[[Int: [Int: Int]]]' 類型的值沒有成員 'keys'
data.sorted(by: { $0.0 < $1.0 })
這會引發錯誤:無法在當前上下文中推斷閉包類型
數據模態
[22 : [24 : 2, 35 : 3]]
鍵是 22。它保存另一個字典 Arrays [Int: Int, Int: Int] 的值
理想情況下,希望結果按鍵排序,即 24、23 和 22。
非常感謝您的幫助。
TL;博士
let asc = data.sorted(by: { $0.keys.first ?? Int.min < $1.keys.first ?? Int.min })
對任何數組進行排序的一般方法是根據您想要的任何屬性適當地比較該數組中的兩個任意值。 在first
和second
之間,如果first
應該在second
之前排序,則返回true
,基於每個屬性的某些屬性。
在這種情況下,每個元素都是一個類型的字典: [Int: [Int: Int]]
。
那么,給定兩個字典,使用哪個屬性來比較?
一般來說,字典可能有零到 N 個鍵,因此您需要決定要在排序邏輯中使用哪個鍵(或鍵組合)。
對於您的特定情況,您可以通過執行dict.keys.first!
(強制解包,因為它是可選的):
let asc = data.sorted(by: { a, b in a.keys.first! < b.keys.first! })
let desc = data.sorted(by: { a, b in a.keys.first! > b.keys.first! })
但是,使用強制展開不是一個好習慣,所以最好通過決定如何處理(假設的)空字典來使用 nil-coalescing,例如首先使用Int.min
處理空字典:
let asc = data.sorted(by: { a, b in a.keys.first ?? Int.min < b.keys.first ?? Int.min })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.