I've been learning Swift lately.
I decided to write a hybrid Swift/Objective-C app that did compute-intensive tasks using the same algorithm implemented in both languages.
The program calculates a large array of prime numbers.
I defined a protocol that both the Swift and the Objective-C version of the calculate object are supposed to conform to.
The objects are both singletons, so I created a typical singleton access method in Objective-C:
+ (NSObject <CalcPrimesProtocol> *) sharedInstance;
The whole protocol looks like this:
#import <Foundation/Foundation.h>
@class ComputeRecord;
typedef void (^updateDisplayBlock)(void);
typedef void (^calcPrimesCompletionBlock)(void);
@protocol CalcPrimesProtocol <NSObject>
- (void) calcPrimesWithComputeRecord: (ComputeRecord *) aComputeRecord
withUpdateDisplayBlock: (updateDisplayBlock) theUpdateDisplayBlock
andCompletionBlock: (calcPrimesCompletionBlock) theCalcPrimesCompletionBlock;
@optional //Without this @optional line, the build fails.
+ (NSObject <CalcPrimesProtocol> *) sharedInstance;
@end
The Objective-C version of the class implements the methods exactly as defined above, no worries.
The swift version has a method:
class func sharedInstance() -> CalcPrimesProtocol
However, if I make that method a required method of the protocol, I get a compiler error "Type "CalcPrimesSwift does not conform to the protocol 'CalcPrimesProtocol'.
If I mark the singleton class method sharedInstance as optional in the protocol, however, it works, and I can invoke that method on either my Swift class or my Objective-C class.
Did I miss some subtlety in the definition of my Swift class method? It seems unlikely, given that I'm able to invoke the sharedInstance() class method on either my Swift class or my Objective-C class.
You can download the project from Github and check it out if you'd like. It's called SwiftPerformanceBenchmark. (link)
In Objective-C, we were always passing around pointers, and pointers could always be
nil
. Lots of Objective-C programmers made use of the fact that sending a message tonil
did nothing and returned0
/nil
/NO
. Swift handlesnil
entirely differently. Objects either exist (nevernil
), or it is unknown whether or not they exist (which is where Swift optionals come into play).Previous to Xcode 6.3, this therefore meant that any Swift code that used any Objective-C code would have to treat all object references as Swift optionals. Nothing about Objective-C's language rules prevented an object pointer from being
nil
.What this meant for using Objective-C protocols, classes, etc., from Swift is that it was a massive mess. We had to choose between to non-perfect solutions.
Given the following Objective-C protocol:
We can either accept the method definition as containing implicitly unwrapped optionals:
This makes the resulting code cleaner (we never have to unwrap within the body), however we will always be at risk of the "found nil while unwrapping optional" error.
Or alternatively, we can define the method as being a true optional:
But this leaves us with a lot of mess unwrapping code.
Xcode 6.3 fixes this problem and adds "Nullability Annotations" for Objective-C code.
The two newly introduced keywords are
nullable
andnonnull
. These are used in the same place you're declaring the return type or parameter type for your Objective-C code.In addition to these two annotation keywords, Xcode 6.3 also introduces a set of macros that makes it easy to mark large sections of Objective-C code as
nonnull
(files with no annotations at all are effectively assumed asnullable
). For this, we useNS_ASSUME_NONNULL_BEGIN
at the top of the section andNS_ASSUME_NONNULL_END
at the bottom of the section we wish to mark.So, for example, we could wrap your entire protocol within this macro pair.
This has the same effect as marking all of the pointer parameters and return types as
nonnull
(with a few exceptions, as this entry in Apple's Swift blog makes note of).Pre-Xcode 6.3
A Swift class that conforms to an Objective-C protocol must treat any Objective-C types in that protocol as optionals.
In trying to figure this out, I created the following Objective-C protocol:
And then, created a Swift class which inherited from
NSObject
and declared itself as conforming to thisObjCProtocol
.I then proceeded to type these method names and let Swift autocomplete the methods out for me, and this is what I got (I put in the method bodies, the rest if autocomplete):
Now, we can use regular optionals (with the
?
) instead of these automatically unwrapped optionals if we want. The compiler is perfectly happy with either. The point is though that we must allow for the possibility ofnil
, because Objective-C protocols cannot preventnil
from being passed.If this protocol were implemented in Swift, we'd get to choose whether the return type is optional or not and Swift would prevent us from returning
nil
to a method that didn't define a non-optional return type.