获取 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"]
Swift 3:
let dictionary: NSDictionary = ["a" : 1, "b" : 2]
let sortedKeys = (dictionary.allKeys as! [String]).sorted(by: <) // ["a", "b"]
在Swift2.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"]
为Swift3
// Initialize the Dictionary
let dict = ["name": "John", "surname": "Doe"]
// Get array of keys
var keys = Array(dict.keys).sorted(by: >)
print(keys)
我有一个以字母作为键的 NSDictionary。我想让这些键按字母顺序排序。我尝试了很多方法,但我在 Sort() 方法上遇到错误。谁能帮我 ????
提前致谢
注意: 1)我不想得到一个排序的字典数组 2)我不想通过值对字典进行排序 (为此我得到了很多答案)
您可以这样对键进行排序:
let dictionary: NSDictionary = ["a" : 1, "b" : 2]
let sortedKeys = (dictionary.allKeys as! [String]).sorted(<) // ["a", "b"]
Swift 3:
let dictionary: NSDictionary = ["a" : 1, "b" : 2]
let sortedKeys = (dictionary.allKeys as! [String]).sorted(by: <) // ["a", "b"]
在Swift2.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"]
为Swift3
// Initialize the Dictionary
let dict = ["name": "John", "surname": "Doe"]
// Get array of keys
var keys = Array(dict.keys).sorted(by: >)
print(keys)