Bird
Raised Fist0
Swiftprogramming~10 mins

Capture lists in closures in Swift - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to capture the variable x in the closure.

Swift
let x = 10
let closure = { [[1]] in
    print(x)
}
closure()
Drag options to blanks, or click blank then click option'
Alet
Bself
Cvar
Dx
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'self' instead of the variable name.
Forgetting to use square brackets.
Using 'var' or 'let' inside the capture list.
2fill in blank
medium

Complete the code to capture the variable count as a copy inside the closure.

Swift
var count = 5
let increment = { [[1] count] in
    print(count + 1)
}
count = 10
increment()
Drag options to blanks, or click blank then click option'
Alet
Bvar
Cself
Dinout
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'var' which captures a mutable reference.
Using 'self' which is for capturing the instance.
Using 'inout' which is not valid in capture lists.
3fill in blank
hard

Fix the error by completing the capture list to avoid a strong reference cycle.

Swift
class Person {
    var name = "Alice"
    lazy var greet: () -> Void = { [[1] self] in
        print("Hello, \(self.name)!")
    }
}
let p = Person()
p.greet()
Drag options to blanks, or click blank then click option'
Avar
Bweak
Cunowned
Dlet
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'var' or 'let' which do not affect reference strength.
Using 'unowned' without understanding lifetime risks.
Not capturing 'self' at all, causing a strong reference cycle.
4fill in blank
hard

Fill both blanks to capture variables a and b as copies inside the closure.

Swift
var a = 1
var b = 2
let closure = { [[1] a, [2] b] in
    print(a + b)
}
a = 10
b = 20
closure()
Drag options to blanks, or click blank then click option'
Alet
Bvar
Cweak
Dunowned
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'var' which captures mutable references.
Using 'weak' or 'unowned' which are for class instances.
5fill in blank
hard

Fill all three blanks to capture self weakly and variables x and y as copies.

Swift
class Calculator {
    var x = 3
    var y = 4
    lazy var compute: () -> Int = { [[1] self, [2] x, [3] y] in
        return x * y + (self?.x ?? 0)
    }
}
let calc = Calculator()
print(calc.compute())
Drag options to blanks, or click blank then click option'
Aweak
Blet
Cvar
Dunowned
Attempts:
3 left
💡 Hint
Common Mistakes
Capturing self strongly causing retain cycles.
Using 'var' instead of 'let' for variables.
Using 'unowned' without ensuring self is always alive.

Practice

(1/5)
1. What is the main purpose of using a capture list in a Swift closure?
easy
A. To control how variables are stored and referenced inside the closure
B. To define the return type of the closure
C. To specify the closure's parameter types
D. To make the closure run asynchronously

Solution

  1. Step 1: Understand what capture lists do

    Capture lists let you specify how variables are captured inside closures, either by strong, weak, or unowned references.
  2. Step 2: Identify the main purpose

    The main purpose is to control how variables are stored and referenced to avoid memory leaks or unexpected behavior.
  3. Final Answer:

    To control how variables are stored and referenced inside the closure -> Option A
  4. Quick Check:

    Capture list purpose = control variable capture [OK]
Hint: Capture lists manage variable references inside closures [OK]
Common Mistakes:
  • Confusing capture lists with closure parameters
  • Thinking capture lists define return types
  • Assuming capture lists affect closure execution timing
2. Which of the following is the correct syntax to declare a capture list with a weak reference to self in a Swift closure?
easy
A. let closure = { [self weak] in print(self) }
B. let closure = { weak self in print(self) }
C. let closure = { [weak self] in print(self) }
D. let closure = { (weak self) in print(self) }

Solution

  1. Step 1: Recall capture list syntax

    Capture lists are declared inside square brackets before the closure parameters, e.g., [weak self].
  2. Step 2: Match correct syntax

    let closure = { [weak self] in print(self) } uses the correct syntax: [weak self] inside square brackets before the closure body.
  3. Final Answer:

    let closure = { [weak self] in print(self) } -> Option C
  4. Quick Check:

    Capture list syntax = [weak self] [OK]
Hint: Capture lists go inside square brackets before closure body [OK]
Common Mistakes:
  • Omitting square brackets around capture list
  • Placing 'weak' outside the brackets
  • Using parentheses instead of brackets
3. What will be the output of the following Swift code?
class Example {
    var value = 10
    lazy var closure: () -> Void = { [unowned self] in
        print(self.value)
    }
}
let example = Example()
example.value = 20
example.closure()
medium
A. 20
B. 10
C. Runtime error
D. nil

Solution

  1. Step 1: Understand unowned self capture

    The closure captures self as unowned, meaning it references the original object without increasing retain count.
  2. Step 2: Check value at closure call

    example.value is updated to 20 before calling closure, so print(self.value) outputs 20.
  3. Final Answer:

    20 -> Option A
  4. Quick Check:

    Unowned self captures current value = 20 [OK]
Hint: Unowned self captures current object state, not copy [OK]
Common Mistakes:
  • Thinking closure captures old value copy
  • Confusing unowned with weak causing nil
  • Expecting runtime error without object deallocation
4. Identify the error in this Swift closure using a capture list:
class Test {
    var count = 0
    lazy var closure: () -> Void = { [weak self] in
        self.count += 1
        print(self.count)
    }
}
medium
A. No error, code is correct
B. Capture list syntax is incorrect
C. Closure cannot be lazy with capture list
D. Cannot use weak self without unwrapping optional

Solution

  1. Step 1: Analyze weak self usage

    When capturing self as weak, self becomes an optional inside the closure.
  2. Step 2: Check code for optional unwrapping

    The code uses self.count directly without unwrapping, causing a compile error.
  3. Final Answer:

    Cannot use weak self without unwrapping optional -> Option D
  4. Quick Check:

    Weak self requires optional unwrapping [OK]
Hint: Weak self is optional; unwrap before use [OK]
Common Mistakes:
  • Using weak self as non-optional
  • Ignoring optional chaining or guard let
  • Assuming lazy closures can't have capture lists
5. You want to create a closure that captures a variable by making a copy of it, so changes outside the closure don't affect the closure's value. Which capture list syntax should you use in Swift?
hard
A. [weak variable]
B. [value = variable]
C. [unowned variable]
D. [copy variable]

Solution

  1. Step 1: Understand capture by copy

    To capture a variable by making a copy, you assign it inside the capture list using syntax like [value = variable].
  2. Step 2: Evaluate options

    [value = variable] uses the correct syntax to copy the variable's value into the closure's capture list.
  3. Final Answer:

    [value = variable] -> Option B
  4. Quick Check:

    Copy capture syntax = [value = variable] [OK]
Hint: Use [newName = oldVar] to capture a copy [OK]
Common Mistakes:
  • Using weak or unowned which capture references
  • Assuming [copy variable] is valid syntax
  • Not assigning variable inside capture list
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard