Junior — Middle
Explain the concept of first-class functions in the Swift language and their role in programming.
sobes.tech AI
Answer from AI
In Swift, functions are first-class objects, which means that functions can:
- Be assigned to variables and constants
- Be passed as arguments to other functions
- Be returned from functions
- Be stored in collections
This allows for more flexible and expressive code, for example, using closures for event handling or behavior configuration.
Example:
func greet(name: String) -> String {
return "Hello, \(name)!"
}
let greeter: (String) -> String = greet
print(greeter("Alice")) // Outputs: Hello, Alice!
First-class functions facilitate functional programming styles, enable high-level abstractions, and simplify working with asynchronous code.