2

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.

  • What might cause the Objective-C function to fail? What behind the scenes issues could cause the creation of the group to not be possible?
  • Why is the Swift version not optional but the Objective-C version is? If creation could fail for any reason why would those same reasons not apply to Swift?
user16217248
  • 3,119
  • 19
  • 19
  • 37
  • 1
    Does seem odd. One would think that Swift's `DispatchGroup` is just a wrapper around Objective-C's `dispatch_group_t`. – HangarRash Apr 11 '23 at 15:24

1 Answers1

2

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Then why does the documentation say *'NULL on failure'* if it will never ever fail? – user16217248 Apr 11 '23 at 19:07
  • 1
    I think that's what I just explained. _Any_ Objective-C initializer can return NULL on failure. That doesn't mean it _will_ and it isn't the (very old) documentation's job to worry about that distinction. All Objective-C code checks to see whether it got `nil`. – matt Apr 11 '23 at 19:49
  • 1
    As an example, ObjC considers the possibility that memory may be exhausted and the required data structures cannot be initialized. In practice, it's basically impossible to actually deal with memory exhaustion in ObjC, and no one really does, but it is considered a legitimate non-fatal failure. Swift does not consider memory exhaustion to be a recoverable error. – Rob Napier Apr 11 '23 at 21:10
  • 1
    Also, there's no need to guess. libdispatch is open source: https://github.com/apple/swift-corelibs-libdispatch/blob/469c8ecfa0011f5da23acacf8658b6a60a899a78/src/semaphore.c#L29-L49 – Rob Napier Apr 11 '23 at 21:14
  • @RobNapier Based on the linked source, they seem to access members of the object pointer without checking if it is `NULL`. So if it fails undefined behavior will have been invoked anyway. – user16217248 Apr 12 '23 at 05:21