In Swift, functions are first-class citizens, meaning they can be treated like any other type. This concept is known as function types, allowing functions to be assigned to variables, passed as arguments, and returned from other functions.
A function type in Swift is defined by its parameter types and return type. The general syntax is:
(parameter types) -> return type
For example, a function that takes two integers and returns their sum would have the type:
(Int, Int) -> Int
Function types can be used in various ways:
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
let mathOperation: (Int, Int) -> Int = add
print(mathOperation(5, 3)) // Output: 8
func applyOperation(_ a: Int, _ b: Int, operation: (Int, Int) -> Int) -> Int {
return operation(a, b)
}
let result = applyOperation(10, 5, operation: add)
print(result) // Output: 15
func makeMultiplier(factor: Int) -> (Int) -> Int {
return { number in number * factor }
}
let timesFive = makeMultiplier(factor: 5)
print(timesFive(6)) // Output: 30
Function types are a powerful feature in Swift, enabling developers to write more expressive and flexible code. They form the foundation for many advanced Swift concepts, including closures and higher-order functions.
To deepen your understanding of Swift function types, explore these related topics: