0
0
Swiftprogramming~10 mins

Closures causing retain cycles 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 declare a closure property in a class.

Swift
class MyClass {
    var closure: (() -> Void)? = [1]
}
Drag options to blanks, or click blank then click option'
Aself
Btrue
C()
Dnil
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-closure values like true or self as initial value.
2fill in blank
medium

Complete the code to capture self weakly in the closure to avoid retain cycles.

Swift
class MyClass {
    var closure: (() -> Void)?
    func setup() {
        closure = { [[1] self] in
            print("Hello")
        }
    }
}
Drag options to blanks, or click blank then click option'
Astatic
Bstrong
Cweak
Dunowned
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'strong' or 'static' which do not prevent retain cycles.
3fill in blank
hard

Fix the error in the closure that causes a retain cycle by adding the correct capture list.

Swift
class MyClass {
    var closure: (() -> Void)?
    func setup() {
        closure = { [1] in
            print(self)
        }
    }
}
Drag options to blanks, or click blank then click option'
A[weak self]
B[strong self]
C[static self]
D[unowned self]
Attempts:
3 left
💡 Hint
Common Mistakes
Not adding a capture list, causing a strong reference cycle.
4fill in blank
hard

Fill in the blank to weakly capture self in the closure.

Swift
class MyClass {
    var closure: (() -> Void)?
    var value: Int = 0
    func setup() {
        closure = { [[1] self] in
            guard let self = self else { return }
            print(self.value)
        }
    }
}
Drag options to blanks, or click blank then click option'
Aweak
Bstrong
Cunowned
Dstatic
Attempts:
3 left
💡 Hint
Common Mistakes
Using unowned without unwrapping, which can cause crashes.
5fill in blank
hard

Fill in the blanks to create a closure that captures self unowned and calls a method safely.

Swift
class MyClass {
    var closure: (() -> Void)?
    func setup() {
        closure = { [[1] self] in
            self.[2]()
        }
    }
    func doWork() {
        print("Working")
    }
}
Drag options to blanks, or click blank then click option'
Aweak
Bunowned
CdoWork
Dwork
Attempts:
3 left
💡 Hint
Common Mistakes
Using weak without unwrapping or calling a wrong method name.