Complete the code to print "Cleanup done" after the function finishes.
func example() {
[1] {
print("Cleanup done")
}
print("Function running")
}The defer statement schedules code to run just before the function returns, perfect for cleanup.
Complete the code to ensure the file is closed after reading.
func readFile() {
let file = openFile()
[1] {
file.close()
}
print("Reading file")
}The defer statement ensures file.close() runs when the function ends, even if errors occur.
Fix the error by completing the code to defer the cleanup print statement.
func process() {
[1] {
print("Cleanup after processing")
}
print("Processing data")
}Only defer correctly delays the cleanup print until the function ends.
Fill both blanks to defer two cleanup print statements in order.
func cleanup() {
[1] {
print("First cleanup")
}
[2] {
print("Second cleanup")
}
print("Function body")
}Using defer twice schedules both cleanup prints to run in reverse order after the function ends.
Fill all three blanks to defer cleanup and print variable values correctly.
func example() {
let x = 10
[1] {
print("Cleanup x: \(x)")
}
let y = 20
[2] {
print("Cleanup y: \(y)")
}
print("Values: \(x), \(y)")
[3] {
print("Final cleanup")
}
}All three defer statements schedule cleanup prints to run in reverse order after the function ends.