Functions
In Swift, functions are first-class citizens, which means you can assign them to variables, pass them as arguments to other functions, and even return them from other functions. Functions in Swift are defined using the func keyword.
Defining Functions
The simplest form of a function takes no parameters and returns Void.
func sayHello() {
print("Hello, world!")
}
Calling Functions
To call a function, you use the function name followed by parentheses.
sayHello() // Output: "Hello, world!"
Parameters
Functions can take parameters.
func greet(name: String) {
print("Hello, \(name)!")
}
When you call this function, you have to provide an argument for the name parameter.
greet(name: "Alice") // Output: "Hello, Alice!"
Return Values
Functions can also return values. The return type of the function is specified after the -> symbol.
func add(a: Int, b: Int) -> Int {
return a + b
}
The function can be called like this:
let sum = add(a: 5, b: 3) // sum is 8
Parameter Labels
Swift allows you to define both an internal name for parameters (used within the function) and an external name (used when calling the function), separated by a space.
func divide(numerator x: Int, denominator y: Int) -> Int {
return x / y
}
let result = divide(numerator: 10, denominator: 2) // result is 5
Variadic Parameters
Some functions are designed to accept a variable number of arguments, indicated by an ellipsis (...) after the type name.
func sum(numbers: Int...) -> Int {
var total = 0
for number in numbers {
total += number
}
return total
}
let total = sum(numbers: 1, 2, 3, 4) // total is 10
Default Parameter Values
You can specify default values for parameters. If a value for that parameter is omitted when the function is called, the default value is used.
func makeCoffee(type: String = "Espresso") {
print("Making a cup of \(type).")
}
makeCoffee() // Output: "Making a cup of Espresso."
makeCoffee(type: "Cappuccino") // Output: "Making a cup of Cappuccino."
In-Out Parameters
In Swift, function parameters are constants by default. If you want a function to modify a parameter value, and you want those changes to persist after the function call, you can use inout parameters.
func modifyValue(_ value: inout Int) {
value *= 2
}
var someValue = 5
modifyValue(&someValue)
// someValue is now 10
Function Types and Higher-Order Functions
Functions have types, just like all other values in Swift. You can use function types to declare variables that can hold functions.
let myFunc: (Int, Int) -> Int = add
Swift supports higher-order functions, meaning you can pass functions as arguments to other functions, and even return functions.
func operate(on a: Int, and b: Int, using operation: (Int, Int) -> Int) -> Int {
return operation(a, b)
}
let result = operate(on: 4, and: 2, using: add) // result is 6
Functions in Swift are extremely flexible and powerful, enabling functional programming patterns, among other things.