Update: As of Xcode 6.3 this is now possible via nullability annotations.
I've been wondering if anyone has figured out a way to explicitly import Obj-C properties into Swift as a optional.
The Problem
Consider the following ObjC class:
@interface Foo : NSObject
@property (strong, nonatomic) NSObject* potentiallyNil;
@end
This is great and all, but when you go to use it in Swift, Xcode tends to import the property as either an instance proper or as an implicitly unwrapped optional.
I've seen this come in as both
class Foo : NSObject {
var potentiallyNil : NSObject
}
as well as
class Foo : NSObject {
var potentiallyNil : NSObject!
}
Now here's the problem with that - within Swift, you've now got this ugly problem of knowing that your property may be nil, but having to avoid the beauty of implicit optional conversion. You're left with one of the following options:
An explicit nil check...
if(potentiallyNil == nil) {
bar()
}
Or a manual conversion to an optional type with an unwrap - also ugly...
let manuallyWrappedPotentiallyNil : NSObject? = potentiallyNil
if let unwrapped = manuallyWrappedPotentiallyNil {
bar();
}
Both of these seem far from ideal. It seems to me there MUST be a way around this! In fact, as @matt has pointed out, Apple has done this themselves throughout the betas while "auditing for optional compliance". Can we do the same?
The Question
It boils down to this: Given the ObjC property
@property (strong, nonatomic) NSObject* potentiallyNil;
is there a way to cause this to be imported to Swift with the signature
var potentiallyNil : NSObject?
Many thanks to all you other iOS/OS X devs out there.
At the time of asking this question, this was not possible. However, in Xcode 6.3, there is a new nullability annotation feature to enable this previously private functionality. Question is therefore no longer relevant.
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