10 Closures

WHAT YOU WILL LEARN IN THIS CHAPTER:                  

  • What closures are
  • Functions as special types of closures
  • How to create a closure as a variable
  • How to write a closure inline
  • How to simplify closures using type inference
  • How to simplify closures using shorthand argument names
  • How to simplify closures using operator functions
  • How to write a trailing closure
  • How to use the Array’s three closure functions: map(), filter(), and reduce()
  • How to declare and use closures in your functions

One of the important features in Swift is the closure. Closures are self-contained blocks of code that can be passed to functions to be executed as independent code units. Think of a closure as a function without a name. In fact, functions are actually special cases of closures.

Swift offers various ways to optimize closures so that they are brief and succinct. The various optimizations include the following:

  • Inferring parameter types and return type
  • Implicit returns from single-statement closures
  • Shorthand argument names
  • Trailing closure syntax
  • Operator closure

UNDERSTANDING CLOSURES

The best way to understand closures is to use an example. Suppose you have the following array of integers:

	let numbers = [5,2,8,7,9,4,3,1]

Assume you want to sort this array in ascending order. You could write your own function to perform the sorting, or you could use the sorted() function available ...

Get Beginning Swift Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.