Book Image

Mastering Swift

By : Jon Hoffman
Book Image

Mastering Swift

By: Jon Hoffman

Overview of this book

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

Standalone closures and good style guidelines


Closures give us the ability to truly separate the data portions of our code from the user interface and business logic portions. This gives us the ability to create reusable classes that focus solely on retrieving our data. This is especially good for developing classes and frameworks that are designed to retrieve data from external services, such as web services, databases, or files. This section will show how to develop a class that will execute a closure once our data is ready to return.

Let's begin by creating a class that will contain the data portion of our code. In this example, the class will be named Guests and it will contain an array of guests names. Let's take a look at the following code:

class Guests {
    var guestNames = ["Jon","Kim","Kailey","Kara","Buddy","Lily","Dash"]
   
    typealias UseArrayClosure = [String] -> Void   
    func getGuest(handler:UseArrayClosure) {
        handler(guestNames)
    }

}

The first line in...