0

I am trying to sort my array by date, I have been trying almost everything but with no results.

This is the closer I got but I get a waring:

Constant 'sortedDate' inferred to have type ()

var Names = [[String]]()

 Names = [
            ["aaa", "bob", "ccc", "26-10-2015 17:50"],
            ["aaa-1", "bbb-1", "ccc-1", "22-10-2015 11:20"],
            ["aaa-2", "bbb-2", "bbb-2", "01-03-2015 17:00"]
        ]

let sortedDate = Names.sortInPlace({ return $0[3].compare($1[3]) == NSComparisonResult.OrderedAscending })

        print("\(sortedDate)")
2
  • You are using the solution I gave you to your earlier question, but you have not accepted my answer. What's my motivation to help you now? Commented Oct 26, 2015 at 23:50
  • hey Matt I was going to accept it I was immerse trying out all the codes.. Done! Commented Oct 26, 2015 at 23:53

1 Answer 1

1

Your data is String, not date. Use an NSDateFormatter to convert it to NSDate:

let names = [
    ["aaa", "bob", "ccc", "26-10-2015 17:50"],
    ["aaa-1", "bbb-1", "ccc-1", "22-10-2015 11:20"],
    ["aaa-2", "bbb-2", "bbb-2", "01-03-2015 17:00"]
]

let formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM-yyyy HH:mm"

let sortedDate = names.sort {
    let date1 = formatter.dateFromString($0[3])
    let date2 = formatter.dateFromString($1[3])
    return date1?.timeIntervalSince1970 < date2?.timeIntervalSince1970
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this is working good however, how can I sort the dates in descending order? using '>' fails

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.