Last active
March 15, 2023 10:12
-
-
Save johnhatvani/a85de2484bdb2c593064 to your computer and use it in GitHub Desktop.
Swift Playground #1 adding components to Date using operator overloading.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
It's fixed now.
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
Swift 3 doesn't have dateByAddingUnit.
`dateByAddingUnit
seems to have been replaced by:
Calendar.current.date(byAdding: .day, value: days, to: date)!`` Although, I can't find options anymore?