Fine-grained interoperation between Objective-C and Swift
suggest changeWhen an Objective-C API is marked NS_REFINED_FOR_SWIFT, Swift imports it with a __ prefix so you can wrap it:
- (NSUInteger)indexOfObject:(id)object NS_REFINED_FOR_SWIFT;
The generated interface exposes __indexOfObject instead of indexOfObject. Replace it with a Swiftier method that returns an optional and hides NSNotFound:
extension NSArray {
func index(of object: Any) -> Int? {
let index = __indexOfObject(object)
guard index != NSNotFound else { return nil }
return index
}
}
In most cases you might want to restrict whether or not an argument to an Objective-C function could be nil. This is done using _Nonnull keyword, which qualifies any pointer or block reference:
void
doStuff(const void *const _Nonnull data, void (^_Nonnull completion)())
{
// complex asynchronous code
}
The compiler then rejects nil from Swift:
doStuff(
nil, // error: nil is not compatible with expected argument type 'UnsafeRawPointer'
nil // error: nil is not compatible with expected argument type '() -> Void'
)
The opposite of _Nonnull is _Nullable, which means that it is acceptable to pass nil in this argument. _Nullable is also the default; however, specifying it explicitly allows for more self-documented and future-proof code.
To further help the compiler with optimising your code, you also might want to specify if the block is escaping:
void
callNow(__attribute__((noescape)) void (^_Nonnull f)())
{
// f is not stored anywhere
}
With this attribute we promise not to save the block reference and not to call the block after the function has finished execution.