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

What is trailing closure syntax?

Câu trả lời

Trailing closure syntax in Swift is a syntactic feature that allows you to write a closure expression outside and after the parentheses of a function call, provided that the closure is the last parameter of the function. This syntax can make the code more readable and concise, especially when the closure is long or complex.

Definition and Usage

A trailing closure is written after the function call's parentheses, even though it is still an argument to the function. When using trailing closure syntax, you do not need to include the argument label for the closure as part of the function call.

Syntax

Here is a basic example to illustrate trailing closure syntax:

func travel(action: () -> Void) {
    print("I'm getting ready to go.")
    action()
    print("I arrived!")
}

// Using trailing closure syntax
travel {
    print("I'm driving in my car")
}

In this example, the travel function takes a closure as its last parameter. Instead of passing the closure inside the parentheses, it is passed directly after the function call.

Benefits

  1. Readability: Trailing closures can make the code more readable by reducing the clutter of nested parentheses and braces.
  2. Conciseness: It allows for more concise code, especially when the closure is the only parameter or the last parameter in the function.

Examples

Without Trailing Closure Syntax

UIView.animate(withDuration: 1, animations: {
    self.view.backgroundColor = UIColor.red
})

With Trailing Closure Syntax

UIView.animate(withDuration: 1) {
    self.view.backgroundColor = UIColor.red
}

Multiple...

middle

middle

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

middle

What’s a strong reference, and why do we need it?

expert

Explain how that code will behave for different Swift versions?

middle

What Classes and Structs have in common in Swift and what are their differences?

Bình luận

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

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