3

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?

Community
  • 1
  • 1
AJ9
  • 1,256
  • 1
  • 17
  • 28
  • As in the referenced thread, NSCalendarOptions is an "OptionSetType". In your case: `let twoDaysAgo = calendar.dateByAddingUnit(.Day, value: -2, toDate: NSDate(), options: [])`. – Martin R Aug 18 '15 at 10:54

2 Answers2

6

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

vadian
  • 274,689
  • 30
  • 353
  • 361
2

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))
AJ9
  • 1,256
  • 1
  • 17
  • 28