NSDate () vs NSDate.date () in Swift

The following is the Bloc.io Swiftris tutorial , where they initialize the date:

lastTick = NSDate.date() 

What causes a compilation error:

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

Which should be equal to:

 NSDate *lastTick = [NSDate date]; 

(from NSDate link )

Apple changed the Swift interface to NSDate , since I saw other examples that use NSDate.date ?

Is it just NSDate or can't you call type methods for any Objective-C APIs?

+42
ios objective-c cocoa swift nsdate
29 oct. '14 at 10:57
source share
4 answers

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

If you are reading the “Using Swift with Cocoa and Objective-C” manual, there is a section on interacting with Objective-C apis:

For consistency and simplicity, Objective-C factory methods are displayed as convenience initializers in Swift. This mapping allows them to be used with the same short syntax as initializers.

Excerpt from: Apple Inc. "Using Swift with Cocoa and Objective-C." interactive books. https://itun.es/gb/1u3-0.l

So the factory method:

 [NSDate date] 

converted to initializer in Swift

 NSDate() 

This is not just NSDate where you will find this template, but also in other Cocoa APIs with factory methods.

+74
Oct 29 '14 at 11:52
source share

NSDate() seems to be a new syntax. NSDate.date() work,

but now you should use NSDate()

+11
Oct 29 '14 at 11:14
source share

In Objective-C, [NSDate date] simply calls [[NSDate alloc] init] . Therefore, you do not need to call NSDate.date() in Swift. Just calling NSDate() initializes the date object with the current date.

+8
Oct 29 '14 at 11:01
source share

Apple changed Swift interface to NSDate ?

Yes, they did it. For me, the compiler says:

Foundation.NSDate: 3: 26: note: "date ()" is explicitly marked as not available here:

@objc(date) class func date() -> Self!

Therefore, it is explicitly tagged for Swift. This means that it is officially out of date.

+6
Oct 29 '14 at 11:18
source share



All Articles