Book Image

Swift Cookbook

Book Image

Swift Cookbook

Overview of this book

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

Sorting an array of products


In this recipe, we will learn how to manage an array in Swift. Here, we will create an array of products (very typical), add products to it, remove unavailable products, and sort the array by price.

Getting ready

Create a new Swift single view project called Chapter 2 SortingProduct.

How to do it...

Let's create and sort an array of products by following these steps:

  1. Before we start with the view part, let's create the model part of our application. In our case, we will create the Product class. So, create a new file called Product.swift and type the following code:

    class Product: Printable {
        var name:String
        var price:Double
        var available:Bool
        
        init(name:String, price:Double, available:Bool){
            self.name = name
            self.price = price
            self.available = available
        }
        
        var description: String {
            return "\(self.name): \(self.price)£ available: \(self.available)"
        }
    }
  2. As you can see, the idea of this class is to create...