Book Image

Swift Cookbook

By : Costa
Book Image

Swift Cookbook

By: Costa

Overview of this book

If you are an experienced Objective-C programmer and are looking for quick solutions to many different coding tasks in Swift, then this book is for you. You are expected to have development experience, though not necessarily with Swift.
Table of Contents (13 chapters)
12
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...