![](/img/trans.png)
[英]How to get all keys and values into separate String arrays from NSDictionary in 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.