sorting - How do I sort Swift objects by multiple criteria -
i have list of swift objects i'd sorted multiple criteria. objects in list of type daterange
:
class daterange { var from: nsdate? var to: nsdate? }
the list contains many of these objects from
or to
fields nil. want have list sorted by:
from
or to
) and @ end objects without any the dates don't matter, existence. in ruby (if date nil
set low date):
date_ranges.sort { |a, b| [fix_nil(a.from), fix_nil(a.to)] <=> [fix_nil(b.from), fix_nil(b.to)] }.reverse def fix_nil(val) val.nil? ? date.new(0) : val end
what's best way swift? in advance.
seems might thought add together datecount
computed property daterange
type. time pattern matching:
extension daterange { // returns number of non-nil nsdate members in 'from' , 'to' var datecount: int { switch (from, to) { case (nil, nil): homecoming 0 case (nil, _): homecoming 1 case (_, nil): homecoming 1 default: homecoming 2 } } }
then can sort list simple closure:
var ranges = [daterange(nil, nil), daterange(nsdate(), nil), daterange(nil, nsdate()), daterange(nil, nil), daterange(nsdate(), nsdate())] ranges.sort { $0.datecount > $1.datecount }
if wanted, create comparable
few more lines:
extension daterange : comparable { } func ==(lhs: daterange, rhs: daterange) -> bool { homecoming lhs.datecount == rhs.datecount } func <(lhs: daterange, rhs: daterange) -> bool { homecoming lhs.datecount > rhs.datecount }
this lets sort list operator argument:
ranges.sort(<)
sorting swift
No comments:
Post a Comment