Why you should be using nullable/nonnull when calling objective-c code in Swift ?

Let’s say you have the following method in objective-c

-(void) sayHelloDefault:(NSString*) name;

-(void) sayHelloDefault:(NSString*) name {
    NSLog(@"Default my name is %@", name);
}

When you import this in Swift, you will be importing the code as follows

vc.sayHelloDefault(String!)

As you can see from the above code, you are actually importing as implicitly unwrapped optionals. This can be a problem, if you are trying to unwrap a null object.

You can try to resolve this by using the following code snippet.

-(void) sayHelloNonnull:(nonnull NSString*) name;
-(void) sayHelloNullable:(nullable NSString*) name;

-(void) sayHelloNonnull:(nonnull NSString*)name {
    NSLog(@"Nonnull my name is %@", name);
}

-(void) sayHelloNullable:(nullable NSString*) name {
    NSLog(@"NULLABLE my name is %@", name);
}

By using nullable and nonnull, you can actually tell the swift compiler whats the type that needs to be imported.

You can simplify the process of annotating your Objective-C code by marking entire regions as audited for nullability. Within a section of code demarcated by the NS_ASSUME_NONNULL_BEGIN and NS_ASSUME_NONNULL_END macros, you only need to annotate the nullable type declarations. Unannotated declarations within the audited region are treated as nonnullable.

You can read more about it here:

https://developer.apple.com/documentation/swift/designating-nullability-in-objective-c-apis

Leave a Reply

Your email address will not be published. Required fields are marked *