【Swift - 使用 Dictionary Key 為 Dictionary 做排序】

撰寫 App 無可避免常要跟 JSON 的資料格式打交道,想必大家都知道 JSON 格式的物件(以’{‘開始,以’}’结尾)是無序的,所謂無序就是每一次取出的順序都會是不一樣的,很顯然這並不是我們要的結果,所以在我們把 JOSN 格式的資料轉成物件存放在記憶體後,我們還得必須對它做排序的處理,如此才能將資料正確的呈現在畫面上,而法蘭克今天就要來介紹兩種處理 Dictionary 排序的方法。


  • 方式一

利用 LazyMapCollection 的函式,結果為回傳一個已排序好的 key 陣列。

public func sorted(by areInIncreasingOrder: (Element, Element) -> Bool) -> [Element]

areInIncreasingOrder 這個 closure 可用 「<」 或「 >」來表示「由小排到大」或「由大排到小」。


  • 方式二

利用 Dictionary 自有的函式,結果為回傳一個已排序好的 Dictionary 陣列。

public func sorted(by areInIncreasingOrder: ((key: Key, value: Value), (key: Key, value: Value)) -> Bool) -> [(key: Key, value: Value)]

第 10 行 => 該閉包所捕獲的兩個參數(firstDictionary, secondDictionary)為 Tuple,可以把它想像成 Dictionary 中的 Dictionary。

第 11 行 => 透過 .0 來取出第 1 和 第 2 個 Tuple 的 key 值出來做比較。「<」表示「由小排到大」,「>」表示「由大排到小」。

第 14 行 => 結果為一 Dictionary 陣列。


不過有時侯天不從人願,後端人員把 Dictionary 的 key 值定義為 Item1、Item2、Item3 … Item10,如果再使用原本的方法做排序,很遺憾的結果並不是我們想要的。

結果為:Item1、Item10、Item2 … Item9。

那我們該怎麼辦呢?其實不難,我們可以取出 Item 之後的字串再轉成 Int 後來做比較即可,用以上的兩種方式再加以修改一下寫法即可。

  • 方式一

第 13~14 行 => 將 Item 字串後的值取出後並轉成 Int。

結果為: [“Item1”, “Item2”, “Item3”, “Item4”, “Item5”, “Item6”, “Item7”, “Item8”, “Item9”, “Item10”]。


  • 方式二

第 13 行 => 取出 Tuple 的第 0 個 index 值的資料,也就是 Dictionary Key。

結果為:[(key: “Item1”, value: “One”), (key: “Item2”, value: “Two”), (key: “Item3”, value: “Three”), (key: “Item4”, value: “Four”), (key: “Item5”, value: “Five”), (key: “Item6”, value: “Siv”), (key: “Item7”, value: “Seven”), (key: “Item8”, value: “Eight”), (key: “Item9”, value: “Nine”), (key: “Item10”, value: “Ten”)]。

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade