Lesson 33Functions
Return Values
Returning Values from Functions
Functions can send values back to the code that called them. This is how you get results from your calculations!
Return Types
Single Value
-> Int, -> String, -> BoolOptional Value
-> Int?, -> String?Tuple (Multiple)
-> (min: Int, max: Int)No Return
No -> (or -> Void)Implicit Return
If your function has only ONE expression, you can skip the return keyword!
Returning Tuples
Tuples let you return multiple values at once! Name them for easy access: result.min, result.max
Early Return with Guard
Use guard to exit early when conditions aren't met. Return nil for optionals!
main.swift
// BASIC RETURN VALUE
func add(a: Int, b: Int) -> Int {
return a + b
}
let result = add(a: 5, b: 3)
print(result) // 8
// IMPLICIT RETURN (single expression)
func multiply(a: Int, b: Int) -> Int {
a * b // No 'return' needed!
}
// RETURNING DIFFERENT TYPES
func isEven(_ number: Int) -> Bool {
return number % 2 == 0
}
func greeting(for name: String) -> String {
return "Hello, \(name)!"
}
// RETURNING OPTIONALS
func findIndex(of value: Int, in array: [Int]) -> Int? {
for (index, element) in array.enumerated() {
if element == value {
return index
}
}
return nil // Not found
}
let numbers = [10, 20, 30, 40]
if let index = findIndex(of: 30, in: numbers) {
print("Found at index \(index)")
}
// RETURNING TUPLES (multiple values!)
func minMax(array: [Int]) -> (min: Int, max: Int) {
var min = array[0]
var max = array[0]
for value in array {
if value < min { min = value }
if value > max { max = value }
}
return (min, max)
}
let bounds = minMax(array: [5, 2, 8, 1, 9])
print("Min: \(bounds.min), Max: \(bounds.max)")
// OPTIONAL TUPLE RETURN
func minMax2(array: [Int]) -> (min: Int, max: Int)? {
if array.isEmpty { return nil }
return (array.min()!, array.max()!)
}
// EARLY RETURN WITH GUARD
func divide(_ a: Int, by b: Int) -> Int? {
guard b != 0 else {
print("Cannot divide by zero!")
return nil
}
return a / b
}
// NEVER RETURNING (crashes or infinite loop)
func fatalError(_ message: String) -> Never {
print(message)
// This function never returns
}Try It Yourself!
Create a function `getStats(for numbers: [Int])` that returns a tuple with (sum, average, count) of the array!