Jecky Jecky - 6 months ago 50
Swift Question

How to Sort an array in an ascending order swift 2.3

[{
msg = "Hi This is Jecky";
name = Susheel;
sender = 77;
timestamp = 1464241769520;
username = susheel;
}, {
msg = Dubai;
name = Jecky;
sender = 78;
timestamp = 1464246547147;
username = Jecky;
}, {
msg = "How are you ?";
name = Susheel;
sender = 77;
timestamp = 1464243480381;
username = susheel;
}, {
msg = "Aje dekhai nai";
name = Jecky;
sender = 78;
timestamp = 1464244974198;
username = Jecky;
}]



  • I have an array like this. I want to sort this array using timestamp in swift 2.3 or latest version of swift. Can anyone help me for this ?


Answer
let array=[
            [
                "msg":"Hi This is Jecky",
                "name":"Susheel",
                "sender":77,
                "timestamp":1464241769520,
                "username":"susheel",
            ],
            [
                "msg":"Dubai",
                "name":"Jecky",
                "sender":78,
                "timestamp":1464246547147,
                "username":"Jecky",
            ],
            [
                "msg":"How are you ?",
                "name":"Susheel",
                "sender":77,
                "timestamp":1464243480381,
                "username":"susheel",
            ],
            [
                "msg":"Aje dekhai nai",
                "name":"Jecky",
                "sender":78,
                "timestamp":1464244974198,
                "username":"Jecky",
            ],
        ]
        print("array = \(array)")
        let sortedArray=array.sort { (obj1:[String : NSObject], obj2:[String : NSObject]) -> Bool in
            return (obj1["timestamp"] as! Int) < (obj2["timestamp"] as! Int)
        }
        print("sortedArray = \(sortedArray)")