NSDate() vs NSDate.date() in Swift

max picture max · Oct 29, 2014 · Viewed 37k times · Source

I´m following along with the Bloc.io Swiftris tutorial where they initialize a date by:

lastTick = NSDate.date()

Which causes a compile error:

'date()' is unavailable: use object construction 'NSDate()'

Which should equal:

NSDate *lastTick = [NSDate date];

(from the NSDate reference)

Did Apple change the Swift interface to NSDate, since I have seen other examples that use NSDate.date?

Is this just NSDate or can you not call type methods for any Objective-C APIs?

Answer

bandejapaisa picture bandejapaisa · Oct 29, 2014

[NSDate date] is a factory method for constructing an NSDate object.

If you read the guide "Using Swift with Cocoa and Objective-C", there is a section on interacting with Objective-C apis:

For consistency and simplicity, Objective-C factory methods get mapped as convenience initializers in Swift. This mapping allows them to be used with the same concise, clear syntax as initializers.”

Excerpt From: Apple Inc. “Using Swift with Cocoa and Objective-C.” iBooks. https://itun.es/gb/1u3-0.l

So the factory method:

[NSDate date]

is converted into an initializer in Swift

NSDate()

It's not just NSDate where you will find this pattern, but in other Cocoa API's with factory methods.