簡體   English   中英

獲取nsdictionary的所有鍵在swift中按字母順序排序?

[英]Get all keys of nsdictionary sorted alphabetically in swift?

我有一個帶字母表的NSDictionary作為鍵。 我想按字母順序排列這些鍵。 我嘗試了很多方法但是我在Sort()方法上遇到錯誤。 誰能幫我 ????

提前致謝

注意:1)我不想得到排序的字典數組2)我不想通過值對字典進行排序(我得到了很多答案)

您可以這樣對鍵進行排序:

let dictionary: NSDictionary = ["a" : 1, "b" : 2]
let sortedKeys = (dictionary.allKeys as! [String]).sorted(<) // ["a", "b"]

斯威夫特3:

let dictionary: NSDictionary = ["a" : 1, "b" : 2]
let sortedKeys = (dictionary.allKeys as! [String]).sorted(by: <) // ["a", "b"]

在Swift 2.2中

您可以按升序排序

let myDictionary: Dictionary = ["a" : 1, "b" : 2]
let sortedKeys = myDictionary.keys.sort()          // ["a", "b"]

降序排列

let myDictionary: Dictionary = ["a" : 1, "b" : 2]
let sortedKeys = myDictionary.keys.sort(>)        // ["b", "a"]

對於Swift 3

    // Initialize the Dictionary
let dict = ["name": "John", "surname": "Doe"]

// Get array of keys

var keys = Array(dict.keys).sorted(by: >)
print(keys)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM