/swift-gcd-wrapper

A wrapper on Swift GCD to make use of queues, qos, synchronous and asynchronous execution easily.

Primary LanguageSwift

swift-gcd-wrapper

This wrapper was based on Swift 2.3. Swift 3 came with a more friendly API for GCD. This wrapper is now obsolete.

A wrapper on Swift GCD to make use of queues, qos, synchronous and asynchronous execution easily.

In order to hide GCD specifics logic and avoid calling dispatch_async, dispatch_sync, creating customs queues or asking for the main or an specific background queue, I've created this wrapper.

This wrapper is also part of an effort to show how to use different kind of queues from GCD and is used as an explanatory example in my blog Lady&Tech.

Basic structure of the wrapper

basic structure

The protocol Executor requires the existence of a dispatch queue.

Executor defines a function to allow the execution of a block, specifying if the execution mode: Async or Sync.

        var queue : dispatch_queue_t { get }

        func execute(mode: QueueExecutionMode, block: dispatch_block_t)

An extension on Executor defines a default implementation of the execute method.

        func execute(mode: QueueExecutionMode, block: dispatch_block_t) {
         switch mode {
         case .Async: dispatch_async(self.queue, block)
         case .Sync: dispatch_sync(self.queue, block)
         }
        }

There are three kind of queues, represented as structs, that you can use to execute your blocks:

  • MainQueue
  • BackgroundQueue
  • CustomQueue

GCD queues

MainQueue is mapping to the system serial main queue.
BackgroundQueue uses the system default provided background concurrent queues, according to the quality of service indicated.
CustomQueue wraps a serial or concurrent queue with a given name.

Read more about QOS and energy efficiency guideline