Changing functionality
Closures also give us the ability to change the functionality of types on the fly. In Chapter 11, Generics, we saw 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 in. In this section, we will show you how to write a function whose functionality can be changed with a closure.
Let's begin by defining a type that will be used to demonstrate how to swap out a functionality. We will name this type TestType
:
struct TestType {
typealias GetNumClosure = ((Int, Int) -> Int)
var numOne = 5
var numTwo = 8
var results = 0;
mutating func getNum(handler: GetNumClosure) -> Int {
results = handler(numOne,numTwo)
print("Results: \(results)")
return results
}
}
We begin this type by defining a typealias
for our closure, which is named...