Skip to content
Learn Netverks

Lesson

Step 25/36 69% through track

closures-swift

Closures

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Closures: the syntax, patterns, and safety habits you need before advancing in Swift.

Teams still ship Closures in Swift codebases—skipping it leaves gaps in debugging and code reviews.

You will apply Closures in contexts like: iPhone/iPad/Mac apps, server-side Swift (niche), and Apple toolchain projects.

Write Swift in main.swift with print(), click Run on server—the dev runner swiftc compiles and runs the binary (requires Swift toolchain, typically macOS; LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

Closures are self-contained function values—like lambdas in Kotlin or arrow functions in JavaScript. Swift provides trailing closure syntax and shorthand argument names.

Syntax

let add = { (a: Int, b: Int) -> Int in a + b }

let nums = [1, 2, 3]
let doubled = nums.map { $0 * 2 }

Capturing values

Closures capture surrounding variables—use capture lists [weak self] in class contexts to avoid retain cycles (covered with ARC).

Important interview questions and answers

  1. Q: Trailing closure syntax?
    A: When the last parameter is a closure, move it outside parentheses—animate { ... }.
  2. Q: @escaping vs non-escaping?
    A: Non-escaping closures run before the function returns; escaping closures may run later—stored or async callbacks must be @escaping.

Self-check

  1. What does $0 mean in a closure?
  2. When must a closure parameter be @escaping?

Tip: Trailing closure syntax: nums.map { $0 * 2 } when the last parameter is a closure.

Interview prep

Trailing closure?

Last closure argument can move outside parentheses.

@escaping?

Closure may outlive the function—stored or async callbacks.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Escaping closure?
  • [weak self]?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump