It seems like it would be nice to add the computed dateCount property to your DateRange type. This would be a good time to match patterns:
extension DateRange { // returns the number of non-nil NSDate members in 'from' and 'to' var dateCount: Int { switch (from, to) { case (nil, nil): return 0 case (nil, _): return 1 case (_, nil): return 1 default: return 2 } } }
Then you can sort the list with a simple close:
var ranges = [DateRange(nil, nil), DateRange(NSDate(), nil), DateRange(nil, NSDate()), DateRange(nil, nil), DateRange(NSDate(), NSDate())] ranges.sort { $0.dateCount > $1.dateCount }
If you want, you can even make it Comparable with a few more lines:
extension DateRange : Comparable { } func ==(lhs: DateRange, rhs: DateRange) -> Bool { return lhs.dateCount == rhs.dateCount } func <(lhs: DateRange, rhs: DateRange) -> Bool { return lhs.dateCount > rhs.dateCount }
This allows you to correctly sort the list with the operator argument:
ranges.sort(<)
source share