Swift·Swift from optionals to SwiftUI

Closures

Pass behaviour with closure syntax and capture lists.

Beginner 12 min read Lesson 6 of 300 Challenge included
What you will be able to do
  • Use trailing closure syntax.
  • Mark escaping closures that outlive the call.
  • Use capture lists to avoid retain cycles.
  • Keep closures small.

In plain English

Closures are functions without a name. Escaping closures can outlive the call, so capture self explicitly and use weak or unowned when retaining the owner would create a cycle.

Closures.swiftSwift
func load(completion: @escaping (Result<[Lesson], Error>) -> Void) {
    // async work later
    completion(.success([]))
}

let names = [Lesson].init().map { $0.title }
print(names)
Your turn

Capture self weakly

Medium

Write a capture list for a closure that uses self weakly.

SWIFT · starter
{ self.load() }
Check your understanding before moving on.
Knowledge checkQuestion 1

Which annotation marks a closure that escapes the function?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Concurrency
Lesson 6 of 300 · 0% of course