简体   繁体   中英

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

I have a dictionary defined as [String: AnyObject] like so:

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]?'

What am I doing wrong?

My variable json is:

({"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. As the error notes, the type you need is [(key: String, value: AnyObject)] (an array of tuples).

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?

Since you have not provided your actual JSON I will have to guess a little. But as others have told you, you should not rely on the order of keys in a Dictionary . You can always sort just the keys and access your Dictionary accordingly. Since sorted will return an Array the following Playground should show you the effects:

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 . This line will not work since Any cannot implement Codable so it should be replaced by the "real thing". The current version will give you NSArray objects as values in your dict which are a pain to work with. Your code will benefit greatly from a proper definition (if possible).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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