tezvyn:

Closures and trailing closure syntax

AI-drafted, machine-checkedintermediate
WHAT IT TESTS

first-class functions and capture.

OUTLINE

closures are self-contained function blocks that capture surrounding state; a final closure parameter can be passed as a trailing closure outside the parentheses.

WHAT THIS TESTS It checks core Swift fluency: whether you understand closures as first-class values that capture context and know the syntactic sugar that makes APIs read cleanly.

WHAT CLOSURES ARE A closure is a self-contained block of functionality you can pass around and call later. Closures are reference types and they capture, by reference, the constants and variables from the surrounding scope they use, keeping that state alive as needed. Global functions and nested functions are special cases of closures. Because they are first-class, you can store them in variables, pass them as parameters, and return them.

TRAILING CLOSURE SYNTAX When a function's final parameter is a closure, Swift lets you write that closure after the call's closing parenthesis instead of inside it, which reads much better for blocks of code. If the closure is the only argument, you can omit the parentheses altogether. Multiple trailing closures are also supported, with the first unlabeled and the rest labeled.

A SIMPLE EXAMPLE Define a function func perform(times: Int, action: () -> Void). Calling it as perform(times: 3) { print("hi") } uses trailing closure syntax: the action block sits outside the parentheses. The function would loop times times and invoke action each pass.

COMMON WRONG ANSWERS Confusing trailing closure syntax with escaping, which is about whether the closure outlives the call, or with autoclosure, which wraps an expression automatically. Saying closures copy captured values; they capture references by default. Forgetting that the closure must be the final parameter to use the unparenthesized form.

LIKELY FOLLOW-UPS What is an escaping closure? How does capture differ from copying? What is a capture list for? How do multiple trailing closures look at a call site?

ONE CONCRETE EXAMPLE A networking helper exposes func fetch(url: URL, completion: (Data?) -> Void). At the call site you write fetch(url: endpoint) { data in handle(data) }, passing the completion as a trailing closure so the handling code reads as a natural block after the call rather than being crammed inside the argument list.

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.