Brice Brice - 5 months ago 122
Objective-C Question

share DispatchQueue and dispatch_queue_t between Swift3 and Objective-c code

As I am trying to migrate incrementally an App to Swift3 and have objective-C and Swift3 work together, I have solved most problems but the following:

In Objective-C, I used a global serial

in the app to dispatch all database operation as a way to avoid conflicts in writing to the database. Swift3 uses DispatchQueue now:

Is it possible to create a
that uses the same
queue so I can dispatch from Swift3 or Objective c to the same queue and continue to avoid conflict?

The main queue is clearly shared, so I hope it's possible, but couldn't find a way to achieve that for my own queue. So I had so far to pick one language (say Objective-C and dispatch_queue_t) and send all the swift request via an objective wrapper. I hope there is a better way to leverage both language native APIs



TLDR: You can just pass the DispatchQueue object to Objective C, it is the same object as the dispatch_queue_t.

dispatch_queue_t is defined like so in Objective C:

typedef NSObject<OS_dispatch_queue> *dispatch_queue_t;

Internally, a OS_dispatch_queue class exists, which, according to the Swift sources, is mapped to DispatchQueue:

- Name: OS_dispatch_object
  SwiftName: DispatchObject
- Name: OS_dispatch_queue
  SwiftName: DispatchQueue

It is then further extended for Swift-specific API, but that API passes the DispatchQueue object directly into Objective C. See for instance call to _swift_dispatch_sync:

@available(OSX 10.10, iOS 8.0, *)
public func sync(execute workItem: DispatchWorkItem) {
    // _swift_dispatch_sync preserves the @convention(block) for
    // work item blocks.
    _swift_dispatch_sync(self, workItem._block)

_swift_dispatch_sync is implemented like so:

    __swift_shims_dispatch_queue_t queue,
    __swift_shims_dispatch_block_t block)
    dispatch_sync(cast(queue), cast(block));