Update: Starting with Xcode 6.3, this is now possible through zeroing annotations .
I was wondering if anyone figured out a way to explicitly import Obj-C objects into Swift as optional.
Problem
Consider the following ObjC class:
@interface Foo : NSObject @property (strong, nonatomic) NSObject* potentiallyNil; @end
That's great and all, but when you go to use it in Swift, Xcode tends to import the property as its own instance or as an implicitly unwrapped optional.
I saw how it happened as in
class Foo : NSObject { var potentiallyNil : NSObject }
and
class Foo : NSObject { var potentiallyNil : NSObject! }
Now here is the problem with this - in Swift, you got this ugly problem - to know that your property may be zero, but you need to avoid the beauty of an implicit additional transformation. You have one of the following options:
Explicit verification of nil ...
if(potentiallyNil == nil) { bar() }
Or manual conversion to an optional type with unpacking is also ugly ...
let manuallyWrappedPotentiallyNil : NSObject? = potentiallyNil if let unwrapped = manuallyWrappedPotentiallyNil { bar(); }
Both of them seem far from ideal. I think there MUST be a way around this! In fact, as @matt noted, Apple did this on its own in all beta versions, while it was “audited for additional compliance”. Can we do the same?
Question
This boils down to the following: given the ObjC property
@property (strong, nonatomic) NSObject* potentiallyNil;
is there any way to get this to import in signature swift
var potentiallyNil : NSObject?
Many thanks to all of you, other iOS / OS X developers.