Skip to content

Instantly share code, notes, and snippets.

@chrisamanse
Created December 6, 2015 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisamanse/2ab39e31e93d5c11d0b5 to your computer and use it in GitHub Desktop.
Save chrisamanse/2ab39e31e93d5c11d0b5 to your computer and use it in GitHub Desktop.
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