Jan49
Jan49

Reputation: 1818

NSDateComponents.setValue() not working with iOS 7 and lower version

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))

Upvotes: 0

Views: 192

Answers (1)

Martin R
Martin R

Reputation: 539815

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.

Upvotes: 2

Related Questions