Functions in Swift
Functions are self-contained blocks of code that perform a specific task. In Swift, you define a function with the func keyword, give it a name, and call it whenever you need to run that block of code. Think of functions as reusable recipes โ write it once, use it everywhere.
func greet() {
print("Hello, world!")
}
greet() // Hello, world!
Try it Yourself ->
Parameters and Return Types
Functions can accept input values (parameters) and return output values. You specify the parameter types and the return type in the function definition. If a function returns something, you must use the -> arrow followed by the return type.
func add(a: Int, b: Int) -> Int {
return a + b
}
let result = add(a: 5, b: 3)
print(result) // 8
Try it Yourself ->
Named Parameters
Swift functions have both external and internal parameter names. The external name is used when you call the function, and the internal name is used inside the function body. By default, the external and internal names are the same, but you can make them different for clearer code.
func greet(name: String) {
print("Hello, \(name)!")
}
greet(name: "Alice") // Hello, Alice!
// Different external and internal names
func move(from source: String, to destination: String) {
print("Moving from \(source) to \(destination)")
}
move(from: "home", to: "office")
Try it Yourself ->
Return Multiple Values with Tuples
What if you need to return more than one value from a function? Tuples let you bundle multiple values together. This is a clean way to return several related results without creating a whole struct.
func getMinMax(array: [Int]) -> (min: Int, max: Int)? {
guard let min = array.min(), let max = array.max() else {
return nil
}
return (min, max)
}
if let stats = getMinMax(array: [3, 1, 4, 1, 5, 9]) {
print("Min: \(stats.min), Max: \(stats.max)")
// Min: 1, Max: 9
}
Try it Yourself ->
Default Parameter Values
You can give parameters a default value so callers don't always have to provide them. This makes your functions more flexible โ callers can override the default when needed or just use the sensible default you've set.
func power(base: Int, exponent: Int = 2) -> Int {
var result = 1
for _ in 0..<exponent {
result *= base
}
return result
}
print(power(base: 3, exponent: 3)) // 27
print(power(base: 5)) // 25 (uses default exponent of 2)
Try it Yourself ->
Variadic Parameters
Sometimes you want to pass a variable number of arguments to a function. Swift supports this with variadic parameters โ you add three dots (...) after the parameter type, and the function receives the values as an array.
func average(_ numbers: Double...) -> Double {
let total = numbers.reduce(0, +)
return Double(total) / Double(numbers.count)
}
print(average(1, 2, 3, 4, 5)) // 3.0
print(average(10, 20)) // 15.0
Try it Yourself ->