Search code examples
swiftsortingnsmutabledictionary

Swift (Xcode 7.3.1) and sorting using values in a Dictionary


I have an array of dictionaries that appears as below and I want to sort and store it such that the objects are sorted based on the 'value' of the 'Like' key ? How do I do this in Swift ? Thanks.

{
    Dislike = 0;
    Like = 5;
    userName = T; }
{
    Dislike = 0;
    Like = 0;
    userName = S; }
{
    Dislike = 0;
    Like = 10;
    userName = N; }

Solution

  • I suppose that's an array of dictionaries?

    If it is the case, you can sort them as follows

    //AnyObject in case your number is an NSNumber
    var array: [[String:AnyObject?]] = yourArray 
    
    array.sort{ $0["Like"]!! > $1["Like"]!! }
    

    basically it mutates the array and sort based on the "Like" key.