Swift Functions
A function is a named block of code that performs a specific task. You define it once and call it as many times as needed. Functions prevent repetition and make code easier to understand.
The Recipe Card Analogy
┌─────────────────────────────────────────────┐
│ A recipe card = A function │
│ │
│ Recipe name: "Make Tea" │
│ Ingredients: water, tea bag, milk │
│ Steps: boil, steep, add milk │
│ Output: one cup of tea │
│ │
│ Call it once or a hundred times — │
│ the steps never change. │
└─────────────────────────────────────────────┘
Defining and Calling a Function
func greet() {
print("Hello! Welcome to Swift.")
}
greet() // Hello! Welcome to Swift.
greet() // Hello! Welcome to Swift.
The func keyword defines a function. The function name is followed by parentheses and a code block. Writing greet() anywhere calls it.
Functions with Parameters
func greetUser(name: String) {
print("Hello, \(name)!")
}
greetUser(name: "Arjun") // Hello, Arjun!
greetUser(name: "Neha") // Hello, Neha!
Parameters pass information into a function. Each call can send different values, making the function flexible.
Functions with Multiple Parameters
func addNumbers(a: Int, b: Int) {
print("\(a) + \(b) = \(a + b)")
}
addNumbers(a: 10, b: 25) // 10 + 25 = 35
Functions that Return a Value
func multiply(a: Int, b: Int) -> Int {
return a * b
}
let result = multiply(a: 6, b: 7)
print(result) // 42
The -> Int tells Swift this function sends back an integer. The return keyword delivers that value to the caller.
Function Flow Diagram
┌──────────────────────────────────────────────────┐
│ Call: multiply(a: 6, b: 7) │
│ │
│ Input: a = 6, b = 7 │
│ ↓ │
│ Process: 6 * 7 │
│ ↓ │
│ Output: 42 (returned to caller) │
│ ↓ │
│ let result = 42 │
└──────────────────────────────────────────────────┘
Argument Labels and Parameter Names
func fly(from origin: String, to destination: String) {
print("Flying from \(origin) to \(destination)")
}
fly(from: "Delhi", to: "Mumbai")
// Flying from Delhi to Mumbai
Swift lets you use two names per parameter. The first (from, to) is the label used when calling the function. The second (origin, destination) is the name used inside the function body. This makes function calls read like sentences.
Omitting Argument Labels
func square(_ number: Int) -> Int {
return number * number
}
print(square(8)) // 64
The underscore _ removes the label requirement at the call site. square(8) is cleaner than square(number: 8).
Default Parameter Values
func orderCoffee(size: String = "Medium") {
print("Ordered a \(size) coffee.")
}
orderCoffee() // Ordered a Medium coffee.
orderCoffee(size: "Large") // Ordered a Large coffee.
Parameters can have default values. When the caller skips a parameter, Swift uses the default.
Functions with Multiple Return Values
func minMax(numbers: [Int]) -> (min: Int, max: Int) {
return (numbers.min()!, numbers.max()!)
}
let result = minMax(numbers: [3, 7, 1, 9, 4])
print("Min: \(result.min), Max: \(result.max)")
// Min: 1, Max: 9
A function can return a tuple to send back multiple values at once. You access each value by name.
