Book Image

Swift Cookbook

Book Image

Swift Cookbook

Overview of this book

Table of Contents (18 chapters)
Swift Cookbook
About the Author
About the Reviewers

Creating a priority list

Let's imagine that we need to manage a queue of passengers on a flight. We know that the business class should embark first, then passengers of the first class, and finally, the economy class.

This is a typical case of a priority queue, but the nagging question is, can we create a priority queue only once? Or should we create a new priority queue in every new app? An Objective-C programmer who recently arrived at Swift probably will create this container storing objects of the type AnyObject. This solution can be acceptable; however, Swift has a better solution that is even safer: as you know, that is generics.

A priority queue needs to organize its elements using criteria. In this case, we can create our queue of any element but ensure that it is created for elements of a class which implements the Comparable protocol, that's what we call a type constraint.

Getting ready

Create a new Swift single view project called Chapter3 Flight.

How to do it...

Follow these steps...