4

I have an array called myArray in which dictionaries are added I want that dictionary to be sorted by time which is a key in dictionary. And that time is in String. The date format of time is "yyyy/MM/dd HH:mm:ss"

I tried with below code solution but gives a warning of "Cast from 'String?' to unrelated type 'Date' always fails".

let sortedArray = self.myArray.sorted{ ($0["Time"] as? Date)! > ($1["Time"] as? Date)! }
print(sortedArray)

If anyone can help me out, Thank You.

4
  • Can you specify you time format? Commented Apr 22, 2017 at 7:57
  • I did that in question @Rahul Commented Apr 22, 2017 at 7:58
  • You can use DateFormatter Commented Apr 22, 2017 at 8:00
  • BTW, this idiom of yours (v as? T)! is quite funny ;-) Next time, you can simply do v as! T bro. I highly recommend taking the time to fully learn Swift Optionals — gonna help you a lot long term! Commented Apr 22, 2017 at 15:30

4 Answers 4

7

You don't need to convert to date time for this sort. The international format (yyyy/MM/dd HH:mm:ss) you're using provides the right sorting order as a string.

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

2 Comments

nice idea to compare:)
To make this clear, your code becomes let sortedArray = self.myArray.sorted{ ($0["Time"])! > ($1["Time"])! }
4

You have to convert string into date using this code:

 let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss"
    let date = dateFormatter.date(from: "2017/04/22 00:00:00") ?? Date()

So, use this:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss"

    let sortedArray = self.myArray.sorted{[dateFormatter] one, two in
     return dateFormatter.date(from:one["Time"] )! > dateFormatter.date(from: two["Time"] )! }

3 Comments

No you don't need to convert the string to date in this case since the date strings are in a sortable format as-is.
FYI - the first bit of code you posted won't work since the string 22-04-2017 00:00:00 does not match the format specifier. The format specifier is correct, the sample date string is not.
@rmaddy I am getting "Binary operator '>' cannot be applied to two 'Any' operands" as I am having array of dictionary of type [String:Any]. in that case we have to convert date string into date..
1
//Sort any dictionary with string dates using any date format
var incisions = [["initials": "B.B. ", "date": "12/18/17 09:39 AM", "patientID": "snowball"], ["patientID": "snowball", "date": "01/03/18 04:03 PM", "initials": "C.J."], ["initials": "B.B. ", "date": "01/04/18 09:47 AM", "patientID": "snowball"]]

func sortArrayDictDescending(dict: [Dictionary<String, String>], dateFormat: String) -> [Dictionary<String, String>] {
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = dateFormat
                return dict.sorted{[dateFormatter] one, two in
                    return dateFormatter.date(from: one["date"]! )! > dateFormatter.date(from: two["date"]! )! }
            }

   //use:
let sortedArray = sortArrayDictDescending(dict: incisions, dateFormat: "MM/dd/yy a")

for i in sortedArray {
 print("incisions \(i["date"]!)")
}

//output:
incisions 01/04/18 09:47 AM
incisions 01/03/18 04:03 PM
incisions 12/18/17 09:39 AM

Comments

0

simple code for sort an array of dictionary with date

let formatter = NSDateFormatter()
formatter.dateFormat = "MMM d, yyyy hh:mm a"
formatter.locale = NSLocale(localeIdentifier: "en_US")

let sorted = displayArray.sort {
    formatter.dateFromString($0["fullfireDate"] as! String)?.compare(formatter.dateFromString($1["fullfireDate"] as! String)!) != .OrderedAscending
    }

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.