Swift Review — Closures(1)

kyrie-eleison
1 min readMar 2, 2021

Source: https://docs.swift.org/swift-book/LanguageGuide/Closures.html

  1. What is a Closure?

We usually think of it as an inline code that succinctly expresses a function. However, according to what the official document of Swift says, closure is a block of codes that executes a certain functionality — which is called a function in other languages.

Then what is exactly a function in Swift anyway? There are three types of closures in Swift:

  • A self-contained block of codes with its name — function
  • A block of codes that “uses” its outer function’s values with its name — nested function
  • A block of codes that “uses” the outer environment’s values without its name — closure expression

So a function is a kind of closure, and it seems that people usually call the last one as “closures” rather than “closure expressions”. In this article, we also follow this “convention”.

2. Why do we use Closures?

Since Swift adopts the Functional Programming Philosophy, we use functions as arguments of other functions. In this case, it is preferable to input functions directly rather than define them with explicit names and put them again.

3. Writing Closures in Neat Ways

Here is an example that one can check how to write a closure succinctly:

--

--