Closures
Pass behaviour with closure syntax and capture lists.
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.
func load(completion: @escaping (Result<[Lesson], Error>) -> Void) {
// async work later
completion(.success([]))
}
let names = [Lesson].init().map { $0.title }
print(names)Your turn
MediumCapture self weakly
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 inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.