I am working on an iOS app and I have data stored in CoreData that I am loading into a UITableView. The data entities have an attribute called id
which is a string
Why to bother with obj-c style's NSSortDescriptor
, In swift we can nicely sort using Swift high order functions - xcode 8.x swift 3.x
class Person: NSObject {
let firstName: String
let lastName: String
let age: Int
init(firstName: String, lastName: String, age: Int) {
self.firstName = firstName
self.lastName = lastName
self.age = age
}
override var description: String {
return "\(firstName) \(lastName)"
}
}
let a = Person(firstName: "a", lastName: "b", age: 24)
let b = Person(firstName: "c", lastName: "d", age: 27)
let c = Person(firstName: "e", lastName: "f", age: 33)
let d = Person(firstName: "g", lastName: "h", age: 31)
let peopleObject = [d, b, a, c]
//SWIFTY
let sortedByFirstNameSwifty = peopleObject.sorted(by: { $0.firstName < $1.firstName })
print(sortedByFirstNameSwifty)//prints[a b, c d, e f, g h]
//Objective c way
let firstNameSortDescriptor = NSSortDescriptor(key: "firstName", ascending: true, selector: #selector(NSString.localizedStandardCompare(_:)))
let sortedByFirstName = (peopleObject as NSArray).sortedArray(using: [firstNameSortDescriptor])
print(sortedByFirstName)//prints [a b, c d, e f, g h]