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?
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.
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.
init() Creates a date value initialized to the current date and time.
[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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With