如何对不同 类 的数组进行排序?
How do I sort an array of different classes?
我有两个 NSManagedObject 类 "Person" 和 "Animal"。 类 都有一个 "name" 属性。如何将它们按字母顺序排列成一个数组?
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)
试试这个:
peopleAndAnimals.sortInPlace {
if let name1 = [=10=].valueForKey("name") as? String,
name2 = .valueForKey("name") as? String {
return name1 < name2
} else {
return false
}
}
我会考虑使用 NSSortDescriptor,这就是我通常按字母顺序排列数组的方式。这是它的 NSHipster 页面 http://nshipster.com/nssortdescriptor/。
我有两个 NSManagedObject 类 "Person" 和 "Animal"。 类 都有一个 "name" 属性。如何将它们按字母顺序排列成一个数组?
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)
试试这个:
peopleAndAnimals.sortInPlace {
if let name1 = [=10=].valueForKey("name") as? String,
name2 = .valueForKey("name") as? String {
return name1 < name2
} else {
return false
}
}
我会考虑使用 NSSortDescriptor,这就是我通常按字母顺序排列数组的方式。这是它的 NSHipster 页面 http://nshipster.com/nssortdescriptor/。