CODEX

Swift 5: Closures Made Simple [Updated in 2022]

Closures are an important concept. This guide aims to make them as simple as possible.

Artturi Jalli
CodeX
Published in
4 min readFeb 4, 2021

--

Photo by Joshua Aragon on Unsplash

Swift Closures in Short

Swift closure is a special type of function. Similar to regular functions, closures accept parameters, execute statements, and return values.

According to Apple:

Closures are self-contained blocks of functionality that can be passed around and used in your code

In Swift, you can use closures as

  • Higher-order functions, such as when sorting or filtering a list.
  • Completion handlers to call back after a lengthy task has finished.

Swift Closures

Let’s start by writing a closure to demonstrate how it works:

let greet = {
print("Hello!")
}
greet()

Output:

"Hello!"

Let’s break it down:

  • We create a constant greet in which we assign a closure. The closure is all the code after the equals sign.
  • We call greet in a similar fashion as if it was a function.

--

--

Artturi Jalli
CodeX

Check @jalliartturi on YouTube to become a successful blogger. (For collabs, reach me out at: artturi@bloggersgoto.com)