Câu hỏi phỏng vấn Swift
Câu hỏi

Explain the defer usage in Swift

Câu trả lời

The defer statement in Swift is a powerful feature used to execute a block of code just before the current scope is exited, regardless of how the exit occurs. This can be particularly useful for cleanup tasks, such as closing file handles, releasing resources, or performing any necessary finalization steps.

Key Points about defer in Swift

  1. Execution Timing:

    • The code within a defer block is executed just before the scope in which it is defined exits. This ensures that the deferred code runs no matter how the scope is exited, whether through a return statement, an error being thrown, or simply reaching the end of the scope[1][2][3][4][5].
  2. Syntax:

    defer {
        // Code to be executed before exiting the scope
    }
  3. Order of Execution:

    • If multiple defer statements are present in the same scope, they are executed in the reverse order of their appearance. This means the last defer statement defined is the first to be executed when the scope exits[1][3][4][5][8].
  4. Common Use Cases:

    • Resource Management: Ensuring that resources such as file handles or network connections are properly closed.
    • Cleanup Tasks: Performing necessary cleanup actions, such as releasing memory or resetting state, before exiting a function or block of code.
    • Error Handling: Ensuring that certain actions are taken even if an error occurs within a block of code[1][3][4][5][7][8].

Examples

Basic Example

func exampleFunction() {
    print("Start")
    defer {
        print("This is deferred until the end")
    }
    print("End")
}

exampleFunction()
// Output:
// Start
// End
// This is deferred until the end

In this example, the defer block is executed after the "End" print statement, just before the function exits[2].

File Handling Example

func readFile() throws {
    let fileHandle = try FileHandle(forReadingFrom: URL(fileURLWithPath: "file.txt"))
    defer {
        fileHandle.closeFile()
    }
    // Read data from file
    let data = fileHandle.readDataToEndOfFile()
    // Process data
}

do {
    try readFile()
} catch {
    print("An error occurred: \(error)")
}

Here, the defer statement ensures that t...

middle

middle

Gợi ý câu hỏi phỏng vấn

middle

In Swift enumerations, what’s the difference between raw values and associated values?

middle

When to use @objc attribute?

expert

What’s the difference between init?() and init() ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào