我正在尝试在Swift中对不同NSManagedObjects的数组进行排序。在Objective-C中,它只需要2行代码(排序描述符和实际排序)。但是,我能想出如何在swift中完成它的唯一方法就是需要几行代码。有没有比我写的代码更好和/或更快的方式?:
var orderMOs = [NSManagedObject]()
orderMOs.append(contentsOf: incidentMOs)
orderMOs.append(contentsOf: transferMOs)
orderMOs.sort (by: {(leftMO, rightMO) -> Bool in
var leftDate: NSDate?
var rightDate: NSDate?
if leftMO is Incident {leftDate = (leftMO as! Incident).createdDate}
else if leftMO is Transfer {leftDate = (leftMO as! Transfer).createdDate}
if rightMO is Incident {rightDate = (rightMO as! Incident).createdDate}
else if rightMO is Transfer {rightDate = (rightMO as! Transfer).createdDate}
if leftDate == nil || rightDate == nil {return true}
return leftDate!.compare(rightDate! as Date) == .orderedDescending
})
答案 0 :(得分:1)
您的两个类都应该符合声明createdDate
的协议。请输入orderMOs
。比你不需要条件演员。
import Foundation
class A {
init(created createdDate: Date) {
self.createdDate = createdDate
}
let createdDate: Date
}
class B {
init(created createdDate: Date) {
self.createdDate = createdDate
}
var createdDate: Date
}
protocol Created {
var createdDate: Date { get }
}
extension A: Created {}
extension B: Created {}
func createDate(year: Int, month: Int, day: Int) -> Date {
var comps = DateComponents()
comps.year = year
comps.month = month
comps.day = day
return Calendar.current.date(from: comps)!
}
var objects = [Created]()
objects.append(A(created: createDate(year: 2018, month: 2, day: 1)))
objects.append(B(created: createDate(year: 2017, month: 12, day: 1)))
objects.append(B(created: createDate(year: 2018, month: 5, day: 18)))
objects.append(A(created: Date()))
将其排序为
objects.sort { (c1, c2) -> Bool in
return c1.createdDate < c2.createdDate
}
您可以做的另一件事是使用带有pattern matching的switch语句来清理代码。
答案 1 :(得分:0)
为什么不在这里使用KVC?
if let leftDate = leftMO.value(forKey: "createdDate") as? Date,
let rightDate = rightMO.value(forKey: "createdDate") as? Date {
if leftDate == nil || rightDate == nil {return true}
return leftDate.compare(rightDate) == . orderedDescending
}