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:

swift Copy
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

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

With Trailing Closure Syntax

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

Multiple...

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?

junior

What is a Serial Queue?

expert

Why can not we just use weak everywhere and forget about unowned ?

Bình luận

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

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