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

Changing functionality


Closures also give us the ability to change the functionality of classes on the fly. We saw in Chapter 9, Working with Generics that generics gave us the ability to write functions that are valid for multiple types. With closures, we are able to write functions and classes whose functionality can change based on the closure that is passed into it as a parameter. In this section, we will show how to write a function whose functionality can be changed with a closure.

Let's begin by defining a class that will be used to demonstrate how to swap out functionality. We will name this class TestClass:

class TestClass {
  typealias getNumClosure = ((Int, Int) -> Int)
  
  var numOne = 5
  var numTwo = 8
  
  var results = 0
  func getNum(handler: getNumClosure) -> Void{
    results = handler(numOne,numTwo)
    return results
  }
}

We begin this class by defining a type alias for our closure that is named getNumClosure. Any closure defined as a getNumClosure closure will...