Safely "unwrapping" Objective-C pointers with nullability specifiers

If I have a non-null pointer in Objective-C and am using it from Swift, it's helpfully bridged as an optional. I can then safely unwrap it using `if let`.


But what if I need to "unwrap" this point in Objective-C? Take this code:


if (result.beacon) {
  [self startShiftWithBeacon:result.beacon]; // Incompatible pointer types sending 'CLBeacon * __nullable' to parameter of type 'CABBeacon * __nonnull'
}


I'd prefer not to cast everywhere, as that's ultimately unsafe, especially over time. Is there already a way to achieve this?

At first I thought there surely will be an easy solution for this, but the more I think about it, Optionals without typesafe unwrapping might not even be possible.

Maybe this works?


if (result.beacon) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnullability-completeness"
    [self startShiftWithBeacon:result.beacon];
#pragma clang diagnostic pop
}


Sure, it's a bit less safe, but at least the type checking will still be done (apart from nullability checking).

Well, the first question I would have is what is a 'CABBeacon' vs a "CLBeacon', but assuming CABBeacon is a subclass thats your actual likely problem, not nullability.


But even assuming nullability was an issue (Obj-C doesn't actually check as deeply as Swift will) in theory there is no reason why 2 seperate calls to 'result.beacon' couldn't initially return an object and then later return nil. The only way to be safe in this case is to assign the return value to a local, then check if that local has a non-nil result, and then pass that on to other locations. Thats basically what happens when Swift unwraps an optional.

Safely "unwrapping" Objective-C pointers with nullability specifiers
 
 
Q