What is trailing closure syntax?
What is trailing closure syntax?
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.
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.
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.
UIView.animate(withDuration: 1, animations: {
self.view.backgroundColor = UIColor.red
})
UIView.animate(withDuration: 1) {
self.view.backgroundColor = UIColor.red
}
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào