3

I'm trying to convert the Objective-C code in this answer, with the correction found in this answer, to Swift:

var theTimeInterval = NSTimeInterval()
var calendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)

var date1 = NSDate()
var date2 = NSDate(timeInterval: theTimeInterval, sinceDate: date1)

var unitFlags = NSCalendarUnit(UInt.max)
var info = calendar.components(unitFlags, fromDate:date1, toDate:date2, options:0)

However, on the finial line, Xcode is giving me an inexplicable error:

Extra argument 'toDate' in call

I looked at the code for NSCalendar by command-clicking it and the function signature I'm using seems to exactly match its components method. So what am I doing wrong?

Community
  • 1
  • 1
Chris Redford
  • 16,982
  • 21
  • 89
  • 109
  • 1
    possible duplicate of [Calculate age from birth date using NSDateComponents in Swift](http://stackoverflow.com/questions/25232009/calculate-age-from-birth-date-using-nsdatecomponents-in-swift) - (Replace `options:0` by `options:nil`) – Martin R Aug 11 '14 at 14:19

2 Answers2

4

I believe this is the correct implementation for Swift 4. Notes:

  • In components use whatever you need
  • Looks like the argument 'options' was removed (see the docs)
    var theTimeInterval = TimeInterval()
    var calendar = Calendar(identifier: .gregorian)

    var date1 = Date()
    var date2 = Date(timeInterval: theTimeInterval, since: date1)

    //NSCalendarUnit from objc are Calendar.Component in swift
    var components: Set<Calendar.Component> = [.hour, .minute, .second]
    var info = calendar.dateComponents(components,
                                       from: date1, to: date2)
Blanc
  • 175
  • 12
-1

This works for me:

var info = calendar.components(unitFlags, fromDate: date1, toDate: date2, options: NSCalendarOptions(0))

You have to write the NSCalentarOptions enum.

Rajesh
  • 10,318
  • 16
  • 44
  • 64