0
0
Swiftprogramming~10 mins

Weak self and unowned self patterns 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 self weakly inside the closure.

Swift
someAsyncFunction { [[1] self] in
    print(self?.description ?? "No self")
}
Drag options to blanks, or click blank then click option'
Aweak
Bunowned
Cstrong
Dstatic
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'unowned' when self might be nil causes crashes.
Forgetting to capture self weakly leads to retain cycles.
2fill in blank
medium

Complete the code to safely unwrap weak self inside the closure.

Swift
someAsyncFunction { [weak self] in
    guard let [1] = self else { return }
    print([1].description)
}
Drag options to blanks, or click blank then click option'
AweakSelf
BselfStrong
Cself
DstrongSelf
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same name 'self' for the constant causes confusion.
Not unwrapping weak self leads to optional usage errors.
3fill in blank
hard

Fix the error in the closure capture list to avoid a retain cycle.

Swift
someAsyncFunction { [[1] self] in
    print(self.description)
}
Drag options to blanks, or click blank then click option'
Aunowned
Bweak
Cstrong
Dstatic
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'strong' causes retain cycles.
Using 'weak' requires optional unwrapping.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that filters and maps with weak self.

Swift
let results = items.compactMap { item in
    guard let [1] = self else { return nil }
    return item.value [2] 10 ? item.key : nil
}
Drag options to blanks, or click blank then click option'
AstrongSelf
B>
C<
Dself
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'self' directly without unwrapping weak self.
Using the wrong comparison operator.
5fill in blank
hard

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

Swift
someAsyncFunction { [[1] self] in
    let message = self.[2] + " is ready"
    print(message)
}
Drag options to blanks, or click blank then click option'
Aunowned
Bstatus
C)
Dweak
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'weak' requires optional unwrapping.
Forgetting to close the print statement causes syntax errors.