0

Are there any functions in Swift 2 that will sort single-dimensional Arrays of NSDate in ascending or descending order without writing my own sorting algorithm?

I've tried the following, but > cannot be used to compare two NSDate objects unfortunately.

var array = [NSDate]()
array.sort { $0 < $1 }
0

2 Answers 2

1

You can take pacification's answer one step further by also declaring that NSDate conforms to Comparable:

public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.isEqualToDate(rhs)
}

public func <(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.compare(rhs) == .OrderedAscending
}

extension NSDate: Comparable { }

Then you can use sort() without providing a comparator:

let dates = [NSDate]()
dates.sort()
Sign up to request clarification or add additional context in comments.

Comments

1

Ok, one way of doing this:

public func <(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.compare(rhs) == .OrderedAscending
}

And then just sort dates like you want:

var array = [NSDate]()
array.sort { $0 < $1 }

2 Comments

Tthere is already a == operator for NSObject, there is no need to implement it for subclasses (like NSDate).
@MartinR, your are right

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.