Junior — Middle
Can you list the different types of closures you know?
sobes.tech AI
Answer from AI
In iOS, closures typically refer to anonymous functions or blocks of code that can capture and use variables from their surrounding context.
Main types of closures:
-
Escaping closures — closures that can be called after the function they are passed to has finished executing. In Swift, the
@escapingkeyword is used for them. -
Non-escaping closures — closures that are called within the function and are not stored after its completion.
-
Autoclosures — closures that are automatically created by the compiler for deferred expression evaluation, often used to simplify syntax.
Example of an escaping closure in Swift:
func performAsyncTask(completion: @escaping () -> Void) {
DispatchQueue.global().async {
// some asynchronous work
completion() // called later
}
}
Closures are widely used for handling asynchronous operations, callbacks, and functional programming.