Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift Evolution Proposal Draft: Conforming NSDate to Comparable

Conform NSDate to Comparable

Introduction

Conform NSDate to the Comparable protocol so that developers could simply use comparison operators on NSDates instead of using compare(_:) -> NSComparisonResult method.

Motivation

Currently, in comparing protocols, developers usually have to extend NSDate to make it to conform to Comparable, or use compare(_:) -> NSComparisonResult method of NSDate. Using comparison operators on NSDates will make the code more readable, such as someDate < today, rather than someDate.compare(today) == .OrderedAscending.

Proposed solution

To implement this, it is as easy as conforming NSDate to Comparable and implementing the global functions <(lhs: NSDate, rhs: NSDate) -> Bool and ==(lhs: NSDate, rhs: NSDate) -> Bool.

Detailed design

extension NSDate: Comparable {}
public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.timeIntervalSinceReferenceDate == rhs.timeIntervalSinceReferenceDate
}
public func <(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.timeIntervalSinceReferenceDate < rhs.timeIntervalSinceReferenceDate
}

Impact on existing code

Swift projects may use comparison operators on NSDates, however, if they have already extended NSDate to conform to Comparable, the code will not compile since it will result to a redundant conformance.

Alternatives considered

An alternative would be to extend NSDate every time in a Swift project instead of fully integrating NSDate conformance to Comparable in Foundation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment