0
0
Swiftprogramming~10 mins

Capture lists in closures in Swift - Interactive Code Practice

Choose your learning style9 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.