0
0
Swiftprogramming~10 mins

Defer statement for cleanup 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 print "Cleanup done" after the function finishes.

Swift
func example() {
    [1] {
        print("Cleanup done")
    }
    print("Function running")
}
Drag options to blanks, or click blank then click option'
Aguard
Bwhile
Cif
Ddefer
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'if' or 'while' instead of 'defer' does not delay execution until function end.
2fill in blank
medium

Complete the code to ensure the file is closed after reading.

Swift
func readFile() {
    let file = openFile()
    [1] {
        file.close()
    }
    print("Reading file")
}
Drag options to blanks, or click blank then click option'
Aguard
Brepeat
Cdefer
Dswitch
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'guard' or 'switch' does not guarantee cleanup after function ends.
3fill in blank
hard

Fix the error by completing the code to defer the cleanup print statement.

Swift
func process() {
    [1] {
        print("Cleanup after processing")
    }
    print("Processing data")
}
Drag options to blanks, or click blank then click option'
Aif
Bdefer
Cguard
Drepeat
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'if' or 'guard' does not delay execution to the end of the function.
4fill in blank
hard

Fill both blanks to defer two cleanup print statements in order.

Swift
func cleanup() {
    [1] {
        print("First cleanup")
    }
    [2] {
        print("Second cleanup")
    }
    print("Function body")
}
Drag options to blanks, or click blank then click option'
Adefer
Bguard
Cif
Drepeat
Attempts:
3 left
💡 Hint
Common Mistakes
Using different keywords for the two blocks breaks the defer behavior.
5fill in blank
hard

Fill all three blanks to defer cleanup and print variable values correctly.

Swift
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")
    }
}
Drag options to blanks, or click blank then click option'
Adefer
Bguard
Cif
Drepeat
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'guard' or 'if' instead of 'defer' breaks the cleanup scheduling.