Coding/Learn/swift/swift closures and functional programming
Swift Foundational Course
01.Introduction, Safety Philosophy & The Toolchain
02.Constants (let), Variables (var) & Type Inference
03.Strings, String Interpolation & Multiline Literals
04.Operators, Range Types & Nil-Coalescing
05.Control Flow: If, Switch Pattern Matching & Guard Statements
06.Optionals, Optional Binding & Optional Chaining
07.Arrays, Sets & Higher-Order Collection Operations
08.Dictionaries, Default Lookups & Tuples
09.Loops, Defer Execution & Labeled Statements
10.Functions, Argument Labels & In-Out Parameters
11.Closures, Trailing Closures & Shorthand Arguments
12.Enums, Raw Values & Associated Values (Tagged Unions)
13.Error Handling: Throwing Functions, Do-Catch & Try Options
14.Structures (struct), Value Semantics & Mutating Methods
15.Classes, Reference Semantics & Inheritance
16.Automatic Reference Counting (ARC), Weak & Unowned References
17.Properties: Stored, Computed, Observers (didSet) & Lazy
18.Protocols, Protocol Extensions & POP (Protocol-Oriented Programming)
19.Generics, Type Constraints & Associated Types
20.Capstone: Production Async/Await Cache & JSON API Engine
Course Certificate0%

Complete all lessons to earn

LearnClosures, Trailing Closures & Shorthand Arguments
11 / 20 0%
Lesson 11 of 20
10 mins read

Closures, Trailing Closures & Shorthand Arguments

PreviousNext Lesson
In Plain English

Closures are self-contained callable blocks of code that can capture references to constants and variables from surrounding context. Master closure expressions ({ (params) -> Return in ... }), trailing closure syntax, shorthand argument names ($0, $1), and @escaping closures.

The Mental Model

"A closure is like a pre-programmed action cartridge: you load it with specific instructions and hand it to a robot (function) that executes the cartridge later when an event finishes."

Deep Dive: How It Works

Closure Expression: { (parameters) -> ReturnType in statements } defines a closure.

Trailing Closure Syntax: If a closure is the final argument to a function, you can write it after the function parentheses (numbers.map { $0 * 2 }).

Shorthand Arguments ($0, $1): Swift provides shorthand names for inline closure arguments in inferred types.

Capturing Values: Closures capture variables by reference from their enclosing scope.

@escaping: Indicates that a closure outlives the function it was passed to (e.g. asynchronous network callbacks).

Syntax Blueprint

let doubled = numbers.map { $0 * 2 }
let sorted = names.sorted { $0 > $1 }
func perform(action: () -> Void) { action() }

Use trailing closure syntax and $0 shorthand for concise functional transformations.

PointCore Rules to Remember

Point star
Trailing Closures: Eliminates ugly closing parentheses when passing closures as the last parameter.
Point star
Type Inference: Swift infers parameter and return types for inline closures automatically.
Point star
Memory Capture: Be mindful of strong reference cycles when capturing self in closures; use [weak self] when needed.

Common Beginner Traps & How to Fix Them

Mistake:Forgetting the in keyword when specifying explicit parameter names: { (x, y) x + y }.

Why it happens: in separates closure parameter declarations from the closure body.

How to fix: Include in: { (x, y) in x + y } or use shorthand: { $0 + $1 }.

Pro Tip: Whenever a closure only has one return expression, you can omit the return keyword entirely.

Live Interactive Example

Hit Run Code to see it live
Custom Sorting and Filtering with Trailing Closures
Swift 5.10 / LLVM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Output Console
Click "Run Code" to view the rendered output.
How it works: Trailing closures filtered seniors and sorted them descending by years of experience.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Transform Numbers with Closures

  • PointDeclare let numbers = [1, 2, 3, 4, 5].
  • PointFilter numbers that are odd ($0 % 2 != 0).
  • PointMultiply remaining numbers by 10 using .map { $0 * 10 }.
  • PointPrint "Transformed: \(result)".
1
2
3
4
5
6
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates