Escaping Closures in Swift

Gabriel Theodoropoulos
7 min readJul 30, 2021
Photo by Emile Perron on Unsplash

Swift is a really powerful programming language, and the number one choice when it comes to make applications for the Apple ecosystem; iOS, macOS, watchOS and tvOS. And as developers who write code in Swift, we make use of closures a lot; a big and important chapter of the language.

Closures is not a topic that a beginner starts with. However, it’s something that everyone has to learn about soon enough. There are various aspects to walk through and understand how they work. Among all those there is a particular one; escaping closures and the @escaping attribute. In this post I will explain what they are and what collateral effects they might bring in an as simple as possible way.

Escaping vs non-escaping closures

When talking about escaping closures, we always refer to closures that we provide as arguments to functions or methods. Generally speaking, we distinguish closures we provide to methods (or functions) in two categories:

  1. Closures that are called before the execution of the method has finished.
  2. Closures that are called after the execution of the method has finished.

In the latter case we are talking about escaping closures; closures that continue to live even after the execution of the method, until we call them at any time later in the…

--

--

Gabriel Theodoropoulos

An iOS & macOS app maker writing code in Swift. Author of countless programming tutorials. Content creator. https://serialcoder.dev