Objective-C crashes when calling Swift async function with a nil completion handler

Hi, I've encountered an issue while working with Swift's async functions and trying to call them from Objective-C.

I have a Swift class that defines an async function asyncFoo as follows:

@objc class SwiftClass: NSObject {
    @objc static let shared = SwiftClass()
    
    private override init() {
    }
    
    @objc func asyncFoo() async {
        print("Start asyncFoo")
        
        // Simulate some asynchronous task
        try? await Task.sleep(nanoseconds: 1_000_000_000) // Sleep for 1 second
        
        print("AsyncFoo completed")
    }
}

Now, I'm trying to call this Swift async function from Objective-C like this:

[[SwiftClass shared] asyncFooWithCompletionHandler:nil];

The problem is, when I pass nil as the completion handler, the app crashes. However, from my understanding, the Swift documentation explicitly states that the completion handler should be _Nullable:

- (void)performWithOperation:(NSString * _Nonnull)operation
           completionHandler:(void (^ _Nullable)(NSInteger))completionHandler;

On the other hand, when I manually generate the Objective-C header file from the Swift code, the completion handler turns out to be _Nonnull.

Could this be a bug? I would appreciate it if someone could provide some clarity on this issue.

2 Likes