Question: I'm working on an iOS project in swift 4.
I have an array of dictionarylike

```
var myArray = [[String: AnyObject]]()

```

The dictionary contains, name, age created\_at(date in string), nationality etc..
And I need to sort the myArray with the ascending order of 'created\_at' key which is string format of date. How can I do that? Please help me. I checked all solutions, but i didnt get the sorted array.

my array is like,

```
(
    {
        name: X
        age: 26
        created_at: "1991-10-10 18:29:05"
        nationality: Indian
    },
    {
        name: Y
        age: 30
        created_at: "2000-05-10 18:29:05"
        nationality: Indian
    },
)

```

Answer: 
I would suggest to create a model for these but of course you can do it like this as well

```
array.sort { (firstItem, secondItem) -> Bool in
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

    if let dateAString = firstItem["created_at"] as? String,
        let dateBString = secondItem["created_at"] as? String,
        let dateA = dateFormatter.date(from: dateAString),
        let dateB = dateFormatter.date(from: dateBString){
        return dateA.compare(dateB) == .orderedAscending
    }
    return false
}

```
In your case, to get a proper result, you sort based on `Date` equality logic but *not* strings. In order to do that, you should get `Date` from the strings first, by knowing the desired format for the given dates (which is `yyyy-MM-dd HH:mm:ss` in your case) thus sort it based on that. Example:

```
let myArray: [[String: AnyObject]] = [["name": "X" as AnyObject, "age": 26 as AnyObject, "created_at": "1991-10-10 18:29:05" as AnyObject],
                                      ["name": "Y" as AnyObject, "age": 30 as AnyObject, "created_at": "2000-05-10 18:29:05" as AnyObject]]

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

let sorted = myArray.sorted { first, second -> Bool in
    guard let firstCreatedAt = first["created_at"] as? String,
          let firstCreatedAtDate = formatter.date(from: firstCreatedAt),
          let secondCreatedAt = second["created_at"] as? String,
          let secondCreatedAtDate = formatter.date(from: secondCreatedAt) else {
        return false
    }

    return firstCreatedAtDate < secondCreatedAtDate
}

print(sorted)
// [["name": X, "age": 26, "created_at": 1991-10-10 18:29:05], ["created_at": 2000-05-10 18:29:05, "name": Y, "age": 30]]

```

Since `Date` conforms to [`Comparable`](https://developer.apple.com/documentation/swift/comparable) protocol, you could simply compare between two dates by using `>` or `<` operators.

***Note:*** Date Strings comparison will also work. So you can just replace `return firstCreatedAtDate < secondCreatedAtDate` with `return firstCreatedAt < secondCreatedAt`.