Junior — Middle
What higher-order functions have you used in your projects, and can you provide examples of their application?
sobes.tech AI
Answer from AI
In iOS development, higher-order functions are often used for processing collections and managing asynchronous operations. For example, methods like map, filter, and reduce are higher-order functions that accept other functions as arguments.
An example of using map to transform an array of numbers:
let numbers = [1, 2, 3, 4, 5]
let squaredNumbers = numbers.map { $0 * $0 }
print(squaredNumbers) // [1, 4, 9, 16, 25]
Closures are also frequently passed to functions for handling events or asynchronous operations:
func fetchData(completion: (Result<String, Error>) -> Void) {
// Simulate asynchronous data loading
DispatchQueue.global().async {
let data = "Data"
completion(.success(data))
}
}
fetchData { result in
switch result {
case .success(let data):
print("Received: \(data)")
case .failure(let error):
print("Error: \(error)")
}
}
Thus, higher-order functions allow writing more expressive and concise code.