user3353890 user3353890 - 1 year ago 78
Swift Question

How do I sort an array of different classes?

I have two NSManagedObject classes "Person" and "Animal". Both classes have a "name" property. How can I sort them alphabetically into a single array?

class Person: NSManagedObject {
@NSManaged var name:String?
@NSManaged var occupation:String?

class Animal: NSManagedObject {
@NSManaged var name:String?
@NSManaged var breed:String?

//This array is filled with both people and animal objects from my database
var peopleAndAnimals = [NSManagedObject]()

peopleAndAnimals.sort(//I want to sort alphabetically by name here)

Answer Source

Try this:

peopleAndAnimals.sortInPlace {
    if let name1 = $0.valueForKey("name") as? String,
           name2 = $1.valueForKey("name") as? String {
        return name1 < name2
    } else {
        return false
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download