Member-only story

What Is The Difference Between @escaping and @nonescaping Closures in Swift?

Escaping sounds fun!

Steven Curtis
5 min readJun 16, 2020
Photo by Billy Chester on Unsplash

An in-depth look into the two types of closures, focussing on @escaping and @nonescaping closures.

Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 11.4.1, and Swift 5.2.2

What are escaping and non-escaping closures

  • A non-escaping closure is a closure that is called within the function it is passed into. The execution of the closure will be before the function returns
  • An escaping closure is a closure that executes after the function it is passed into returns. The closure outlives the function that it is passed into, and this is known as escaping. escaping closures are frequently used for asynchronous execution or storage.

The Problem

Closures risk creating a retain cycle. By writing @escaping before a closure’s parameter type indicates that the closure is allowed to escape (to be called later)

Let us look at some real-life examples

The real-life example

Now a closure can be thought of a set of instructions that are passed to a function…

--

--

No responses yet