DevPrep

All topics › The Swift Language

What is a closure and what does @escaping mean?

Middle PRO

The idea

A closure is a self-contained block of code that can be passed around as a value and that captures variables from its surrounding context. Functions and methods are closures too. Capture is by reference by default: the closure sees the current value of the variable, not a snapshot taken at creation; a capture list [x] makes a copy.

var counter = 0
let byReference = { counter }          // captures the variable (by reference)
let byValue = { [counter] in counter } // capture list: copy at creation time
counter = 5
print(byReference(), byValue())        // 5 0

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store