Junior — Middle
Can you name the main types of closures used in programming?
sobes.tech AI
Answer from AI
In iOS programming (Swift/Objective-C), closures are blocks of code that can be passed around and used as objects.
Main types of closures:
-
Escaping closures — closures that can be called after the function they were passed to has exited. For example, asynchronous operations.
-
Non-escaping closures — closures that are called within the function and are not stored for later use.
-
Autoclosures — closures that are automatically created by the compiler for deferred expression evaluation, often used for optimization.
Example of an escaping closure in Swift:
func fetchData(completion: @escaping (String) -> Void) {
DispatchQueue.global().async {
// simulate data loading
let data = "Data loaded"
completion(data)
}
}
fetchData { result in
print(result)
}
Here, completion is an escaping closure because it is called asynchronously after the function exits.