Although the initializer must return the full NSCalendar object, it looks like it behaves like an implicit extra (NSCalandar!). If you look at the object in the debugger, it will appear as an NSCalendar:
(NSCalendar) $ r1 = 0x0000000000000000 {ObjectiveC.NSObject = parent NULL}
Even stranger, the following code does not generate runtime errors when accessing nil NSCalendar - at least for me:
let x = NSCalendar(calendarIdentifier: "asdasda") let y = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian) if (x.isDateInToday(NSDate())) { println("x works") } if (y.isDateInToday(NSDate())) { println("y works") } if (x == nil) { println("x not calendar") } if (y == nil) { println("y not calendar") }
For me, this displays "y works" and "x is not a calendar." It would be in pure Swift to have a run-time error if using nil is implicit optional, but pqnet indicates that calling the method on the nil pointer in object c does not cause an error, it is simply ignored - this is what seems to be doing. So strange, but in this case it is safe:
let x = NSCalendar(calendarIdentifier: "asdasda") if (x != nil) {
However, a faster way is to use an explicit optional - i.e. do the following:
let x : NSCalendar? = NSCalendar(calendarIdentifier: "asdasda") if let cal = x {
You can also use the implicit optional let x : NSCalendar =... and check with if x != nil as above - your choice seems to be that sometimes different contexts cause implicit or explicit options ...
Edit:
From the Xcode release notes :
Swift does not support object initializers that do not return null. (16480364)! Workaround: If a factory method exists, use it instead. Otherwise, write the result to optional. For instance:
let url: NSURL? = NSURL(string: "not a url")