Can't subclass DispatchGroup - "only visible via the Objective-C runtime"?

1k views Asked by At

It's not possible to subclass DispatchGroup, how to do so?

Note:

this has finally been fixed in iOS 10+

Example, carry a stateful package with a group,

class PushDispatchGroup: DispatchGroup {
    var sentIds: [(tableName: String, rowId: String)] = []
}

thanks to shallowThought for pointing out this is fixed in iOS10.

1

There are 1 answers

7
Rob Napier On BEST ANSWER

how to inherit from a class which is 'only visible via the Objective-C runtime'?

You don't.

This is not wrapped around a proper "object" the way you're thinking about it. It's wrapped around a dispatch_group, which is a C struct. This class is not designed to be subclassed and does not bridge in a normal way to ObjC, so you can't subclass it there either.

"Objects" that bridge directly to low level C types often have very unusual structures that parts of the system are hard-coded to know how to deal with (this happens all the time with toll-free bridging like NSString and CFString). In many cases, the types are designed to be identical in memory layout through careful choice of structure (I haven't picked apart DispatchGroup, but it looks like one from this group). When that's true, you can't add any storage because then the memory layout will be different and you break the bridging.

As various commenters have said, you also shouldn't be doing this, which is why there is no easy answer for how to do this. Classes that are not explicitly designed for subclassing are intentionally difficult or impossible to subclass in Swift (this comes up regularly around less tricky types than DispatchGroup, and the answer is the same: it's intentional; don't do it).