How to create class methods that conform to a protocol shared between Swift and Objective-C?

断了今生、忘了曾经 提交于 2019-11-26 23:04:53

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 to nil did nothing and returned 0/nil/NO. Swift handles nil entirely differently. Objects either exist (never nil), 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:

@protocol ObjCProtocol <NSObject>

@required + (id<ObjCProtocol>)classMethod;
@required - (id<ObjCProtocol>)instanceMethod;
@required - (void)methodWithArgs:(NSObject *)args;

@end

We can either accept the method definition as containing implicitly unwrapped optionals:

class MyClass: NSObject, ObjCProtocol {
    func methodWithArgs(args: NSObject!) {
        // do stuff with args
    }
}

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:

class MyClass: NSObject, ObjCProtocol {
    func methodWithArgs(args: NSObject?) {
        // unwrap do stuff with args
    }
}

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 and nonnull. These are used in the same place you're declaring the return type or parameter type for your Objective-C code.

- (void)methodThatTakesNullableOrOptionalTypeParameter:(nullable NSObject *)parameter;
- (void)methodThatTakesNonnullNonOptionalTypeParameter:(nonnull NSObject *)parameter;
- (nullable NSObject *)methodReturningNullableOptionalValue;
- (nonnull NSObject *)methodReturningNonNullNonOptionalValue;

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 as nullable). For this, we use NS_ASSUME_NONNULL_BEGIN at the top of the section and NS_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.

NS_ASSUME_NONNULL_BEGIN
@protocol CalcPrimesProtocol <NSObject>

- (void) calcPrimesWithComputeRecord: (ComputeRecord *) aComputeRecord
              withUpdateDisplayBlock: (updateDisplayBlock) theUpdateDisplayBlock
                  andCompletionBlock: (calcPrimesCompletionBlock) theCalcPrimesCompletionBlock;
+ (id <CalcPrimesProtocol> ) sharedInstance;

@end
NS_ASSUME_NONNULL_END

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:

@protocol ObjCProtocol <NSObject>

@required + (id<ObjCProtocol>)classMethod;
@required - (id<ObjCProtocol>)instanceMethod;
@required - (void)methodWithArgs:(NSObject *)args;

@end

And then, created a Swift class which inherited from NSObject and declared itself as conforming to this ObjCProtocol.

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):

class ASwiftClass : NSObject, ObjCProtocol {
    class func classMethod() -> ObjCProtocol! {
        return nil
    }

    func instanceMethod() -> ObjCProtocol! {
        return nil
    }

    func methodWithArgs(args: NSObject!) {
        // do stuff
    }
}

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 of nil, because Objective-C protocols cannot prevent nil 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!