Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array of dictionaries in Swift

Tags:

ios

swift

Suppose we have

var filesAndProperties:Dictionary<String, Any>[]=[] //we fill the array later

When I try sorting the array using

filesAndProperties.sort({$0["lastModified"] > $1["lastModified"]})

Xcode says "could not find member subscript".

How do I sort an array of such dictionaries by values in a specific key?

like image 474
Hristo Avatar asked Jul 06 '14 08:07

Hristo


People also ask

Can we sort dictionary in Swift?

Swift Dictionary sorted()The sorted() method sorts a dictionary by key or value in a specific order (ascending or descending).

How do you sort an array in Swift?

To sort the array we use the sort() function. This function is used to sort the elements of the array in a specified order either in ascending order or in descending order. It uses the “>” operator to sort the array in descending order and the “<” operator to sort the array in ascending order.

How do you sort a dictionary in ascending order in Swift?

To sort the values in ascending order, you can use the < operator. Otherwise, you can use the > operator to sort the swift dictionary in descending order.


1 Answers

The error message is misleading. The real problem is that the Swift compiler does not know what type of object $0["lastModified"] is and how to compare them.

So you have to be a bit more explicit, for example

filesAndProperties.sort {
    item1, item2 in
    let date1 = item1["lastModified"] as Double
    let date2 = item2["lastModified"] as Double
    return date1 > date2
}

if the timestamps are floating point numbers, or

filesAndProperties.sort {
    item1, item2 in
    let date1 = item1["lastModified"] as NSDate
    let date2 = item2["lastModified"] as NSDate
    return date1.compare(date2) == NSComparisonResult.OrderedDescending
}

if the timestamps are NSDate objects.

like image 83
Martin R Avatar answered Oct 02 '22 23:10

Martin R