[Swift] Sort custom class(struct) object array

March 22, 2017 0 Comments


//Post structure 
class Post: NSObject {
    var uid: String
    var title: String
    var body: String
    var time: String
    var imagePath : String
    init(uid: String, title: String, body: String, time: String, imagePath: String) {
        self.uid = uid
        self.title = title
        self.body = body
        self.time = time
        self.imagePath = imagePath
    }
}


var postAr = [Post]()

//add element in to array...
........
//Sort array
postAr = postAr.sorted(by: { $0.time > $1.time })


last line is key....In Addition, we can using map, filter or reduce to operate on Swift collection types.

You can see how to use in here






0 comments: