0
0
Swiftprogramming~10 mins

Capturing values from context 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 value of 'number' inside the closure.

Swift
let number = 10
let closure = { print([1]) }
closure()
Drag options to blanks, or click blank then click option'
Anumber
Bself.number
Cnum
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name that is not defined in the current scope.
Trying to use 'self.number' when 'number' is not a property.
2fill in blank
medium

Complete the code to capture the value of 'count' as a constant inside the closure.

Swift
var count = 5
let closure = { [[1]] in
    print(count)
}
count = 10
closure()
Drag options to blanks, or click blank then click option'
Avar count
Bself.count
Clet count
Dcount
Attempts:
3 left
💡 Hint
Common Mistakes
Writing 'var count' or 'let count' inside the capture list, which is invalid syntax.
Not using a capture list and expecting the closure to capture the value at definition time.
3fill in blank
hard

Fix the error in the closure to capture 'self' weakly to avoid retain cycles.

Swift
class MyClass {
    var value = 42
    func doWork() {
        let closure = { [[1] self] in
            print(self.value)
        }
        closure()
    }
}
Drag options to blanks, or click blank then click option'
Avar
Bweak
Cstrong
Dunowned
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'strong' or 'var' in the capture list, which are invalid.
Not capturing 'self' weakly, causing memory leaks.
4fill in blank
hard

Fill both blanks to capture 'value' strongly and 'count' weakly inside the closure.

Swift
var value = 100
var count = 20
let closure = { [[1] value, [2] count] in
    print(value, count ?? 0)
}
closure()
Drag options to blanks, or click blank then click option'
Avalue
Bweak
Cunowned
Dstrong
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to write 'strong value' which is invalid syntax.
Not using 'weak' before 'count' to capture it weakly.
5fill in blank
hard

Fill all three blanks to capture 'name' unowned, 'age' weakly, and 'score' strongly inside the closure.

Swift
var name = "Alice"
var age: Int? = 30
var score = 95
let closure = { [[1] name, [2] age, [3] score] in
    print(name, age ?? 0, score)
}
closure()
Drag options to blanks, or click blank then click option'
Aunowned
Bweak
Cscore
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up the order of capture modifiers and variable names.
Trying to write 'strong score' which is invalid syntax.