Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDate() vs NSDate.date() in Swift

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?

like image 985
max Avatar asked Oct 29 '14 10:10

max


People also ask

What is NSDate in Swift?

The NSDate class provides methods for comparing dates, calculating the time interval between two dates, and creating a new date from a time interval relative to another date.

How do I compare NSDate?

We can also use the earlierDate: and laterDate: methods of the NSDate class: NSDate *earlierDate = [date1 earlierDate:date2];//Returns the earlier of 2 dates. Here earlierDate will equal date2. NSDate *laterDate = [date1 laterDate:date2];//Returns the later of 2 dates.

How do you initialize a date in Swift?

init() Creates a date value initialized to the current date and time.


1 Answers

[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.

like image 50
bandejapaisa Avatar answered Oct 06 '22 01:10

bandejapaisa