So I've just tried what I thought was a simple operation - Adding one day to an NSDate:
Following this answer also on SO which provides the following solution, whilst not exactly what I want (but has the same logic) does not work:
let twoDaysAgo = calendar.dateByAddingUnit(NSCalendarUnit.Day, value: -2, toDate: NSDate(), options: nil)
I get the following error messages:
"Could not find an overload for 'NSDate.init' that accepts the supplied arguments
After removing the NSDate() argument to form this:
let d = NSDate()
let twoDaysAgo = calendar.dateByAddingUnit(NSCalendarUnit.Day, value: -2, toDate: d, options: nil)
I now get a different error:
'Int' is not convertible to 'IntegerListeralConvertible'
After searching various outlets it turns out that the error is in the final argument options:nil- which must now be passed a parameter.
Why is this the case?
NSHipster states:
components(_:fromDateComponents:toDateComponents:options:): Returns the difference between two NSDateComponents instances. The method will use base values for any components that are not set, so provide at the least the year for each parameter. The options parameter is unused; pass nil/0.
Whilst Apple do not explicitly state the argument must not be nil
Options for the calculation. See “Calendar Options” for possible values. If you specify a “wrap” option (NSWrapCalendarComponents), the specified components are incremented and wrap around to zero/one on overflow, but do not cause higher units to be incremented. When the wrap option is false, overflow in a unit carries into the higher units, as in typical addition.
Is this an XCode 7 beta bug? New in Swift 2?
The full signature of dateByAddingUnit:toDate:options in Swift 1.2 and higher is
func dateByAddingUnit(unit: NSCalendarUnit, value: Int, toDate date: NSDate, options: NSCalendarOptions) -> NSDate?
The options type is a clearly a non-optional type so it cannot be nil.
In Swift 1.2 and later you can pass an empty value using the generic initializer of the type, but the type must be distinct
NSCalendarOptions()
There are a lot of changes during the Swift evolution so NSHipster might refer to an early version of Swift
For anyone interested I got the solution to work/compile in the following way:
let calendar = NSCalendar.currentCalendar()
let addOneDay = calendar.dateByAddingUnit(NSCalendarUnit.Day, value: 1, toDate: NSDate(), options: NSCalendarOptions.WrapComponents)
or:
let calendar = NSCalendar.currentCalendar()
let addOneDay = calendar.dateByAddingUnit(NSCalendarUnit.Day, value: 1, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With