Swift: Why class method has return type AnyObject?

932 views Asked by At

NSDate.distantFuture() is documented to return an object of type NSDate.

So then, why does it have a return type of AnyObject, instead of NSDate?

2

There are 2 answers

2
Mark McCorkle On

This is actually documented as returning AnyObject.

returns nil if an event specified in the event mask does not happen before the specified date.

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/#//apple_ref/occ/clm/NSDate/distantFuture**

distantFuture Creates and returns an NSDate object representing a date in the distant future.

Declaration SWIFT class func distantFuture() -> AnyObject OBJECTIVE-C + (id)distantFuture Return Value An NSDate object representing a date in the distant future (in terms of centuries).

Discussion You can pass this value when an NSDate object is required to have the date argument essentially ignored. For example, the NSWindow method nextEventMatchingMask:untilDate:inMode:dequeue: returns nil if an event specified in the event mask does not happen before the specified date. You can use the object returned by distantFuture as the date argument to wait indefinitely for the event to occur.

myEvent = [myWindow nextEventMatchingMask:myEventMask untilDate:[NSDate distantFuture] inMode:NSDefaultRunLoopMode dequeue:YES]; Import Statement import Foundation

Availability Available in OS X v10.0 and later.

1
Nikolai Ruhe On

In Objective-C distantFuture returns an id, not NSDate. Automatic Swift conversion makes this an AnyObject. When the class will be reviewed by Apple they will probably switch that to NSDate.

NSDate's distantFuture is actually from the distant past (at least Mac OS X 10.0, probably even before that). At this time many factory methods returned id because there was no instancetype. It was just to make it easier to call a subclasses method on the returned object.