Skip to content

Instantly share code, notes, and snippets.

@johnhatvani
Last active March 15, 2023 10:12
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnhatvani/a85de2484bdb2c593064 to your computer and use it in GitHub Desktop.
Save johnhatvani/a85de2484bdb2c593064 to your computer and use it in GitHub Desktop.
Swift Playground #1 adding components to Date using operator overloading.
import Foundation
extension Int{
var day: (Int, Calendar.Component) {
return (self, .day)
}
var month: (Int, Calendar.Component) {
return (self, .month)
}
var year: (Int, Calendar.Component) {
return (self, .year)
}
}
////
public func + (date: Date, tuple: (value: Int, unit: Calendar.Component)) -> Date {
return Calendar.current.date(byAdding: tuple.unit, value: tuple.value, to: date)!
}
public func - (date: Date, tuple: (value: Int, unit: Calendar.Component)) -> Date {
return Calendar.current.date(byAdding: tuple.unit, value: (-tuple.value), to: date)!
}
public func += (date: inout Date, tuple: (value: Int, unit: Calendar.Component)) {
date = Calendar.current.date(byAdding: tuple.unit, value: tuple.value, to: date)!
}
public func -= (date: inout Date, tuple: (value: Int, unit: Calendar.Component)) {
date = Calendar.current.date(byAdding: tuple.unit, value: (-tuple.value), to: date)!
}
var tomorrow = Date() + 1.year
tomorrow += 1.day
var yesterday = Date() - 1.day
yesterday -= 1.year
@derrh
Copy link

derrh commented Jul 28, 2014

you could sweeten this up a bit by adding extensions to Int

extension Int  {
    var day: (Int, NSCalendarUnit) {
        return (self, NSCalendarUnit.CalendarUnitDay)
    }
}

This allows you to do:

var tomorrow = NSDate() + 1.day
tomorrow += 1.day

@aflondono
Copy link

I like these overloaded operations. Very nice.

What is the last argument options: NSCalendarOptions.SearchBackwards in dateByAddingUnit?
I was looking around, and I see that other people in similar answers use options: NSCalendarOptions(0), or options: nil, but no one explains what it does. And I cannot find it in Apple's documentation.

@johnhatvani
Copy link
Author

Ive updated this to bring it into swift 1.2 and taken derrh input to add and extension on Int to make the end api cleaner.

As for the Calendar option I have changed it to the only one documented by apple. Which added no real impact on the return of the method

@eonist
Copy link

eonist commented Jan 13, 2017

Swift 3 doesn't have dateByAddingUnit.

`dateByAddingUnitseems to have been replaced by:Calendar.current.date(byAdding: .day, value: days, to: date)!`` Although, I can't find options anymore?

@FilDevTronic
Copy link

It's fixed now.

@stevestevensonneds
Copy link

This is the worst code I've ever seen

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