O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 in. 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 type that will be used to demonstrate how to swap out 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) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required