Nata Mio Nata Mio - 5 months ago 8
iOS Question

Sort Array of objects according to date

I have an

NSMutableArray
containing objects and its called
HistoryObject
, and it has properties date,name,type...etc

i can't find a proper way to sort the array from new to old date for this kind of object.if somebody would explain how can i accomplish that with example !

i have tried the following but its not working:

let sortedArray = HistoryArray.sort({$0.date.compare($1.date) == NSComparisonResult.OrderedAscending })


The date comes in the following format as String :
Jun 26, 2016

Answer

Do it in this way

// Create your model
class Model {
    var date:NSDate!
    var name:String!
}

// Not use the NSArray, but use the swift array with sepecific type of data in it
var array = [Model]()

// fake models
for i in 0..<10 {
    let model = Model()
    model.date = NSDate(timeInterval: Double(i*60), sinceDate: NSDate())
    model.name = "\(i)"
    array.append(model)

}

// then sort using this code
let newArray = array.sort{ $0.date.timeIntervalSince1970 > $1.date.timeIntervalSince1970 }