Changing functionality
Closures also give us the ability to change the functionality of types on the fly. We saw in Chapter 11, Working with Generics, that generics give us the ability to write functions that are valid for multiple types. With closures, we are able to write functions and types 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) -> Int { results = handler(numOne,numTwo) return results } }
We begin this class by defining a type alias for our closure that...