Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly importing Objective-C properties into Swift as optionals

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.

like image 871
mszaro Avatar asked Nov 11 '22 01:11

mszaro


1 Answers

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.

like image 133
mszaro Avatar answered Nov 29 '22 14:11

mszaro