Chapter 8: Collection Iterations With Closures

大綱

Closure basics

  • Closures are so named because they have the ability to “close over” the variables and constants within the closure’s own scope.

    • This simply means that a closure can access, store and manipulate the value of any variable or constant from the surrounding context.

    • Variables and constants used within the body of a closure are said to have been captured by the closure.

var multiplyClosure = { (a: Int, b: Int) -> Int in
  return a * b
}
let result = multiplyClosure(4, 2)

Shorthand syntax

Closures with no return value

  • Just like functions, closures aren’t required to do these things.

    • Void is actually just a typealias for (). This means you could have written () -> Void as () -> ().

Capturing from the enclosing scope

Custom sorting with closures

Iterating over collections with closures

  • In Swift, collections implement some very handy features often associated with functional programming.

Key points

  • Closures are functions without names. They can be assigned to variables and passed as parameters to functions.

    Closures have shorthand syntax that makes them a lot easier to use than other functions.

  • A closure can capture the variables and constants from its surrounding context.

  • A closure can be used to direct how a collection is sorted.

  • A handy set of functions exists on collections that you can use to iterate over a collection and transform it. Transforms comprise mapping each element to a new value, filtering out certain values and reducing the collection down to a single value.

Last updated