简体   繁体   English

Swift 4字典[String:AnyObject]按字母顺序按键排序

[英]Swift 4 Dictionary [String : AnyObject] sort by key in alphabetical order

I have a dictionary defined as [String: AnyObject] like so: 我有一个定义为[String:AnyObject]的字典,如下所示:

let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String : AnyObject]

Now I am trying to put them into alphabetical order by key. 现在,我试图按键将它们按字母顺序排列。 I have tried the following: 我尝试了以下方法:

self.appDelegate.communityArray = json.sorted(by: { $0.0 < $1.0 })

But I get this error: 但是我得到这个错误:

Cannot assign value of type '[(key: String, value: AnyObject)]' to type '[String : AnyObject]?' 无法将类型[[(key:String,value:AnyObject)]'的值分配给类型[[String:AnyObject]?

What am I doing wrong? 我究竟做错了什么?

My variable json is: 我的变量json是:

({"BBB" : Array("aaa", "bbb", "ccc")}, {"AAA" : Array("aaa", "bbb", "ccc")})

What I am trying to get is: 我想要得到的是:

({"AAA" : Array("aaa", "bbb", "ccc")}, {"BBB" : Array("aaa", "bbb", "ccc")})

Your communityArray is the wrong type. 您的communityArray是错误的类型。 As the error notes, the type you need is [(key: String, value: AnyObject)] (an array of tuples). 如错误提示所示,您需要的类型是[(key: String, value: AnyObject)] (元组数组)。

I think the first step is to change 我认为第一步是改变

let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String : AnyObject]

to

let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String : Any]

But I cannot understand why you want to sort a Dictionary.. Maybe You intended to declare variable json as Array? 但是我不明白为什么要对字典排序。也许您打算将变量json声明为Array?

Since you have not provided your actual JSON I will have to guess a little. 由于您尚未提供实际的JSON,因此我不得不稍作猜测。 But as others have told you, you should not rely on the order of keys in a Dictionary . 但是正如其他人告诉您的那样,您不应该依赖Dictionary中键的顺序。 You can always sort just the keys and access your Dictionary accordingly. 您始终可以仅对键进行排序,并相应地访问Dictionary Since sorted will return an Array the following Playground should show you the effects: 由于sorted将返回一个Array因此以下游乐场应该为您显示效果:

import Cocoa

let jsonData = """
    {"BBB" : ["aaa", "bbb", "ccc"], "AAA" : ["aaa", "bbb", "ccc"]}
""".data(using: .utf8)!

do {
    let dict = try JSONSerialization.jsonObject(with: jsonData, options:.allowFragments) as! [String : Any]
    print(dict)
    let array = dict.sorted(by: {$0.0 < $1.0})
    print(array)
    print(type(of:array))
} catch {
    print(error)
}

I would suggest you amend your structure definition in order to make some line like 我建议您修改您的结构定义,以使像

let dict = try JSONDecoder().decode([String:Any].self, from:jsonData)

work inside your do . 在你的内部do This line will not work since Any cannot implement Codable so it should be replaced by the "real thing". 由于Any都无法实现Codable因此此Codable因此应将其替换为“真实的东西”。 The current version will give you NSArray objects as values in your dict which are a pain to work with. 当前版本将为您提供NSArray对象作为dict中的值,很难使用。 Your code will benefit greatly from a proper definition (if possible). 您的代码将从适当的定义(如果可能)中大大受益。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM