user3353890 user3353890 - 5 months ago 7x
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)


Try this:

peopleAndAnimals.sortInPlace {
    if let name1 = $0.valueForKey("name") as? String,
           name2 = $1.valueForKey("name") as? String {
        return name1 < name2
    } else {
        return false