-
Book Overview & Buying
-
Table Of Contents
Mastering Swift 6 - Seventh Edition
By :
A function can accept multiple closure parameters. When these closures are used as trailing closures, they can be written outside of the function’s parentheses, as we saw with a single trailing closure. Each trailing closure is labeled in order to define which parameter it corresponds to. This is especially useful in scenarios where a function may handle different outcomes or behaviors, such as success and failure. Let’s look at an example of this:
func performTask(success: () -> Void, failure: () -> Void) {
let taskSucceeded = Bool.random()
if taskSucceeded {
success()
} else {
failure()
}
}
In this example, the performTask() function accepts two closures as parameters, one named success and one named failure, and then within the function, depending on if the logic succeeds or fails, the appropriate closure is run. In this example, we use a random value to determine success or failure. We...