0

I needed to add one year to the current date (swift & iOS 7 and above). But every solutions i have found is only support iOS 8 and above. Please guide me through proper solution. Thanks

 let components: NSDateComponents = NSDateComponents()
    components.setValue(1, forComponent: NSCalendarUnit.Year);
    let date: NSDate = NSDate()
    let expirationDate = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: date, options: NSCalendarOptions(rawValue: 0))
Jan
  • 1,744
  • 3
  • 23
  • 38

1 Answers1

2

The setValue() method of NSDateComponents is only available on iOS 8/OS X 10.9 or later:

components.setValue(1, forComponent: NSCalendarUnit.Year)

For iOS 7 support, simply use

components.year = 1

Also note that

dateByAddingComponents(components, toDate: date, options: NSCalendarOptions(rawValue: 0)

can be written shorter as

dateByAddingComponents(components, toDate: date, options: [])

compare for example Swift 2.0 calendar components error.

Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382