Book Image

Swift Cookbook

By : Cecil Costa, Cecil Costa
Book Image

Swift Cookbook

By: Cecil Costa, Cecil Costa

Overview of this book

Table of Contents (18 chapters)
Swift Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating a protocol for the priority queue


In the previous recipe, we could create a generic code, which can be used in our future programs, but we have to remember that priority queues are only one kind of queue. It is good practice to define an interface for this abstract data type, and after this, have different implementations.

As you know, in Swift, we have protocols for cases such as this; however, we have a problem; protocols don't have generics. What is the solution? The answer is associated types.

Getting ready

Copy the project of the previous recipe and name it Chapter 3 Flight Protocol, and create a new file called Queue.swift.

How to do it...

To create a protocol for the priority queue, follow these steps:

  1. Add the following code onto the Queue.swift file:

    protocol Queue {
        typealias ElementType
        func enqueue(element:ElementType)
        func dequeue() -> ElementType
        var size: Int{
            get
        }
    }
  2. Now, return to the priority queue and change its header to this one:

    class PriorityQueue...