What are Swift closures?

Why Interviewers Ask This

Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid Swift & iOS basics — a prerequisite for any developer role.

Answer

Closures are self-contained blocks of code that can capture and store references to variables and constants from the surrounding context. They're first-class citizens — can be assigned to variables, passed as function parameters, and returned from functions. Closure syntax: { (parameters) -> ReturnType in body }. Examples: // Full syntax: let multiply = { (a: Int, b: Int) -> Int in return a * b } // Trailing closure: let sorted = [3, 1, 4, 1, 5].sorted { $0 < $1 } // Shorthand argument names ($0, $1): let doubled = [1, 2, 3].map { $0 * 2 } // Trailing closure: let filtered = [1, 2, 3, 4].filter { $0 > 2 } // Multiline trailing: URLSession.shared.dataTask(with: url) { data, response, error in guard let data = data else { return } processData(data) }. Capturing values: func makeCounter() -> () -> Int { var count = 0 return { count += 1; return count } // Captures count } let counter = makeCounter() counter() // 1 counter() // 2. @escaping: when a closure is stored and called after the function returns: func fetchData(completion: @escaping (Data) -> Void). @autoclosure: wraps an expression in a closure automatically: func log(_ message: @autoclosure () -> String) { if isDebug { print(message()) } }. Capture list [weak self]: button.action = { [weak self] in self?.doSomething() } — prevents retain cycles.

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Swift & iOS codebase.