Sort Dictionary Alphabetically Cannot assign value of type '[(key: String, value: AnyObject)]' to type 'Dictionary?'

前端 未结 2 1990
刺人心
刺人心 2021-01-18 07:45

I have this Dictionary, which I am getting from a web service:

let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! Dictiona         


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-18 08:45

    As mentioned in the comments a dictionary – a collection type containing key-value pairs – is unordered by definition, it cannot be sorted.

    The sorted function of collection applied to a dictionary treats the dictionary for example

    ["foo" : 1, "bar" : false]
    

    as an array of tuples

    [(key : "foo", value : 1), (key : "bar", value : false)]
    

    and sorts them by key (.0) or value (.1) (I suspect sorting by value Any will raise a compiler error)

    The error occurs because you cannot assign an array of tuples to a variable declared as dictionary. That's almost the literal error message.

    As a compromise I recommend to map the dictionary to a custom struct (similar to a tuple but better to handle)

    struct Community {
        let key : String
        let value : Any
    }
    

    Your variable name already implies that you want a real array

    var communityArray = [Community]()
    
    let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary
    communityArray = json.map { Community(key: $0.0, value: $0.1 }.sorted { $0.key < $1.key } 
    

提交回复
热议问题