9

When comparing two Dates in swift, I can compare using >, but not <. startTime, endTime and Date() are all of type Date (previously NSDate)

   //Broken Code
   if Date() >= startTime && Date() < endTime
   {
       ...
   }
   Gives ambiguous use of < operator error

  //Working Code
   if Date() >= startTime && endTime > Date()
   {
       ...
   }

Is there a specific reason this isn't working?

I actually found this example when trying to find the apple documentation, and they actually use this code http://www.globalnerdy.com/2016/08/29/how-to-work-with-dates-and-times-in-swift-3-part-3-date-arithmetic/

I started wondering if maybe it was the using of the && operator, or possibly just being an issue of the order, but even doing the code by itself as

if startTime < endTime {...}

But it returns the same order.

Obviously I have found the workaround, But I am very curious why this is happening.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Dallas
  • 1,788
  • 2
  • 13
  • 24
  • try `if (Date() >= startTime) && (Date() < endTime) {` – Leo Dabus Sep 17 '16 at 01:00
  • @LeoDabus I should have put this in the code above, I actually did try that, acted like it wanted to work, and then after maybe 10-12 seconds the compiler came back and gave the same error. Another thing I tried was casting each specifically as a Date, I saw that elsewhere on SO. – Dallas Sep 17 '16 at 01:00
  • try cleaning your project. both should work – Leo Dabus Sep 17 '16 at 01:03
  • 3
    I suspect you have extended NSDate to conform to comparable protocol, which it is not needed for Date (Swift 3) – Leo Dabus Sep 17 '16 at 01:05
  • 1
    @LeoDabus I thought I commented that out! Thanks a ton, I am fixing all the errors from going to swift 3, and came across these before the error in the extension. – Dallas Sep 17 '16 at 01:10
  • 1
    @LeoDabus feel free to put that as an answer, And ill accept it. – Dallas Sep 17 '16 at 01:12

1 Answers1

25

You have probably extended NSDate to conform to comparable protocol in Swift 2. Just remove it because Date now conforms to Comparable protocol in Swift3.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • 12
    When some random dude from the Internet knows my code better than I do… – Ian Bytchek Jan 12 '17 at 22:15
  • 1
    The exact same scenario here: two Dates compared; < complains about being ambiguous, while > works. Indeed, NSDate was previously extended and made to adhere to Comparable (by whoever wrote the Swift2.x version of the app) and the < operator was overwritten. JUST the < operator :-) Leo Dabus, how on earth did you know ??? :-) – Florin Odagiu Feb 06 '17 at 13:04
  • 1
    It took me a while to figure out, but I had the following code from Swift 2 which I needed to REMOVE. static public func <(a: Date, b: Date) -> Bool { return a.compare(b) == ComparisonResult.orderedAscending } – Dale Clifford Mar 08 '18 at 22:48