swiftobjective-cnulldispatchgroup

Why can Objective-C dispatch_group_create() return NULL but not Swift DispatchGroup()?


I noticed a disparity between the Swift API for dispatch groups and the Objective-C API.

The init() for DispatchGroup() returns a non optional value.

But the Objective-C dispatch_group_create() mentions a possibility for a NULL return:

Return Value

The newly created group, or NULL on failure.


Solution

  • In Objective-C, any object reference can be nil, and any call to an object initializer must cope with the possibility that nil might be returned.

    In Swift, therefore, every Objective-C object would theoretically need to be an Optional — and in Swift 1 this was indeed the case: They were all implicitly unwrapped Optionals. Later, though, every single Objective-C object reference in Swift was hand-tweaked to be either a normal Optional or an ordinary non-Optional, depending on whether it could truly ever by nil or not.

    Well, the object that you get when you call dispatch_group_create() therefore can theoretically be nil, in fact it never will be. The creators of the Swift-style DispatchQueue code knew this, and so the DispatchGroup initializer is not nullable.