這是我按position
屬性對元素進行排序時的方法。 DBSet
和DBItem
都有該屬性。如何在Swift中使用兩種對象對數組進行排序?
@objc(DBCategory)
class DBCategory: NSManagedObject {
@NSManaged var identifier: String
@NSManaged var items: Set<DBItem>
@NSManaged var sets: Set<DBSet>
}
這是我如何使用它
private var elements = [AnyObject]()
private func prepareElements() {
elements.removeAll(keepCapacity: false)
if let items = currentCategory?.items {
for item in items {
elements.append(item)
}
}
if let sets = currentCategory?.sets {
for set in sets {
elements.append(set)
}
}
elements.sort {
var previousPosition = 0
var currentPosition = 0
if let set = $0 as? DBSet {
previousPosition = Int(set.position)
}
if let item = $0 as? DBItem {
previousPosition = Int(item.position)
}
if let set = $1 as? DBSet {
currentPosition = Int(set.position)
}
if let item = $1 as? DBItem {
currentPosition = Int(item.position)
}
return previousPosition < currentPosition
}
}
position
是Int16
型我如何簡化?
你能同時顯示你的兩個對象類型的聲明? (DBSet和DBItem) –
他們來自核心數據... –