0
0
Swiftprogramming~10 mins

Memory implications of captures 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 a variable in a closure.

Swift
var count = 0
let increment = { count [1] 1 }
Drag options to blanks, or click blank then click option'
A*=
B-=
C+=
D/=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-=' will decrease the count instead of increasing it.
Using '*=' or '/=' will multiply or divide, which is not intended here.
2fill in blank
medium

Complete the code to create a closure that captures a constant.

Swift
let multiplier = 3
let multiply = { (value: Int) -> Int in
    return value [1] multiplier
}
Drag options to blanks, or click blank then click option'
A*
B/
C-
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' will add instead of multiply.
Using '-' or '/' will subtract or divide, which is not the intended operation.
3fill in blank
hard

Fix the error in the closure that causes a strong reference cycle.

Swift
class Counter {
    var count = 0
    lazy var increment: () -> Void = {
        self.count [1] 1
    }
}
Drag options to blanks, or click blank then click option'
A*=
B+=
C/=
D-=
Attempts:
3 left
💡 Hint
Common Mistakes
Using other operators will cause wrong arithmetic.
Not capturing 'self' weakly can cause a memory leak (not fixed in this blank).
4fill in blank
hard

Fill both blanks to capture self weakly and safely unwrap it inside the closure.

Swift
class Logger {
    var message = "Hello"
    lazy var log: () -> Void = { [[1] self] in
        guard let self = self else { return }
        print(self.message)
    }
}
Drag options to blanks, or click blank then click option'
Astrong
Bstatic
Cunowned
Dweak
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'strong' or 'static' is incorrect for capture lists.
Using 'unowned' can cause crashes if self is nil.
5fill in blank
hard

Fill all three blanks to create a closure that captures self unowned and uses it safely.

Swift
class Downloader {
    var url = "https://example.com"
    lazy var download: () -> Void = { [[1] self] in
        print("Downloading from \(self.[2])")
        // Use self carefully to avoid retain cycles
        let task = URLSession.shared.dataTask(with: URL(string: self.url)!) { data, response, error in
            if let data = data {
                print("Downloaded \(data.count) bytes")
            }
        }
        task.[3]()
    }
}
Drag options to blanks, or click blank then click option'
Aunowned
Burl
Cresume
Dweak
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'weak' instead of 'unowned' can require optional unwrapping.
Forgetting to call resume() will not start the download.