I have a Swift based iOS application. I am trying to use one of the Swift sort methods to sort my array of objects by the "createdAt" NSDate
property.
My array has a bunch of PFObject
- these objects have different properties including an NSDate
property called "createdAt".
All I want to do, is to order the array so that the objects which are the oldest, are sent to the bottom of the array.
Here is my code:
let sortedArray = (self.statusData.copy() as! NSArray).sortedArrayUsingComparator { (obj1, obj2) -> NSComparisonResult in
if (((obj1 as! PFObject).createdAt?.compare((obj2 as! PFObject).createdAt!)) == NSComparisonResult.OrderedDescending) {
return obj2
}
else {
return obj1
}
}
However when I try to return the objects, I get the following error:
Cannot convert return expression of type 'AnyObject' to return type 'NSComparisonResult'
I don't understand whats wrong, why can't I just return the date comparison result which is determined my if statement?
Thanks for your time, Dan.
Your problem is that it's expecting a return type of NSComparasonResult
and you're returning anAnyObject
. However, you are already getting an NSComparasonResult
in your existing code. Therefore, simply replace all of that with this:
let sortedArray = (self.statusData.copy() as! NSArray).sortedArrayUsingComparator { (obj1, obj2) -> NSComparisonResult in
return (obj1 as! PFObject).createdAt?.compare((obj2 as! PFObject).createdAt!)
}