0
0
Swiftprogramming~10 mins

Deinitializers 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 define a deinitializer in a Swift class.

Swift
class FileHandler {
    init() {
        print("File opened")
    }
    [1] {
        print("File closed")
    }
}
Drag options to blanks, or click blank then click option'
Adestroy
Binit
Cfunc cleanup()
Ddeinit
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'init' instead of 'deinit' for cleanup.
Trying to name the deinitializer as a normal function.
2fill in blank
medium

Complete the code to print a message when the object is deallocated.

Swift
class Connection {
    init() {
        print("Connected")
    }
    deinit {
        [1]("Disconnected")
    }
}
Drag options to blanks, or click blank then click option'
Arelease
Bprint
Clog
Ddisconnect
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-existent function like 'release' or 'disconnect'.
Forgetting to call a function to output the message.
3fill in blank
hard

Fix the error in the deinitializer syntax.

Swift
class Logger {
    [1] {
        print("Logger destroyed")
    }
}
Drag options to blanks, or click blank then click option'
Ainit
Bdeinit()
Cdeinit
Dfunc deinit()
Attempts:
3 left
💡 Hint
Common Mistakes
Adding parentheses after 'deinit'.
Using 'func' keyword before 'deinit'.
4fill in blank
hard

Fill both blanks to create a class that opens a file and closes it when the object is destroyed.

Swift
class FileManager {
    init() {
        [1]("File opened")
    }
    [2] {
        print("File closed")
    }
}
Drag options to blanks, or click blank then click option'
Aprint
Binit
Cdeinit
Dfunc
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'func' keyword before 'deinit'.
Not using 'print' to show messages.
5fill in blank
hard

Fill all three blanks to create a class that tracks resource allocation and cleans up properly.

Swift
class Resource {
    var id: Int
    init(id: Int) {
        self.id = id
        [1]("Resource \(id) allocated")
    }
    [2] {
        [3]("Resource \(id) released")
    }
}
Drag options to blanks, or click blank then click option'
Aprint
Bdeinit
Dinit
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'init' instead of 'deinit' for cleanup.
Forgetting to use 'print' to show messages.