17

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?

2 Answers 2

43

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Here, The problem is that compiler unable to understand type that what of object $0["lastModified"] is.

if the timestamps are floating point numbers:-

filesAndProperties = filesAndProperties.sorted(by: {
                (($0 as! Dictionary<String, AnyObject>)["lastModified"] as? Double)! < (($1 as! Dictionary<String, AnyObject>)["lastModified"] as? Double)!
            })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.