Swift Return Values

Getting results back from functions

â†Šī¸ What are Return Values?

Return values allow functions to send data back to the code that called them. Instead of just performing actions, functions can calculate results and return them for use elsewhere.


func addNumbers(a: Int, b: Int) -> Int {
    return a + b
}

let result = addNumbers(a: 5, b: 3)
print("The sum is: \(result)")
                                    

Output:

The sum is: 8

Return Value Concepts

🔄

Return Type

Specify what type of data to return

func getName() -> String {
    return "John"
}
📤

Return Keyword

Use 'return' to send data back

func double(x: Int) -> Int {
    return x * 2
}
đŸŽ¯

Single Expression

Omit 'return' for single expressions

func square(x: Int) -> Int {
    x * x
}
📊

Multiple Returns

Return tuples for multiple values

func getInfo() -> (String, Int) {
    return ("Alice", 25)
}

🔹 Basic Return Syntax

Functions specify return type with arrow (->) and return keyword:

// Function that returns a String
func getGreeting() -> String {
    return "Hello, World!"
}

// Function that returns an Int
func getAge() -> Int {
    return 25
}

// Function that returns a Bool
func isAdult(age: Int) -> Bool {
    return age >= 18
}

// Use the returned values
let greeting = getGreeting()
let userAge = getAge()
let adult = isAdult(age: userAge)

print(greeting)
print("Age: \(userAge)")
print("Is adult: \(adult)")

Output:

Hello, World!

Age: 25

Is adult: true

🔹 Mathematical Functions

Return values are perfect for calculations:

// Basic math operations
func add(a: Int, b: Int) -> Int {
    return a + b
}

func multiply(a: Double, b: Double) -> Double {
    return a * b
}

func calculateArea(width: Double, height: Double) -> Double {
    return width * height
}

// Using the functions
let sum = add(a: 10, b: 5)
let product = multiply(a: 3.5, b: 2.0)
let area = calculateArea(width: 4.0, height: 6.0)

print("Sum: \(sum)")
print("Product: \(product)")
print("Area: \(area) square units")

Output:

Sum: 15

Product: 7.0

Area: 24.0 square units

🔹 Implicit Returns

For single expressions, you can omit the 'return' keyword:

// Explicit return (traditional way)
func doubleExplicit(number: Int) -> Int {
    return number * 2
}

// Implicit return (shorter way)
func doubleImplicit(number: Int) -> Int {
    number * 2
}

// More examples of implicit returns
func isEven(number: Int) -> Bool {
    number % 2 == 0
}

func getFullName(first: String, last: String) -> String {
    "\(first) \(last)"
}

func getMax(a: Int, b: Int) -> Int {
    a > b ? a : b
}

// Test the functions
print(doubleExplicit(number: 4))
print(doubleImplicit(number: 4))
print(isEven(number: 7))
print(getFullName(first: "John", last: "Doe"))
print(getMax(a: 10, b: 15))

Output:

8

8

false

John Doe

15

🔹 Returning Multiple Values

Use tuples to return multiple values from a function:

// Return multiple values as a tuple
func getPersonInfo() -> (name: String, age: Int, city: String) {
    return ("Alice", 28, "New York")
}

func calculateStats(numbers: [Int]) -> (min: Int, max: Int, average: Double) {
    let minimum = numbers.min() ?? 0
    let maximum = numbers.max() ?? 0
    let sum = numbers.reduce(0, +)
    let average = Double(sum) / Double(numbers.count)
    
    return (minimum, maximum, average)
}

// Use the returned tuples
let person = getPersonInfo()
print("Name: \(person.name)")
print("Age: \(person.age)")
print("City: \(person.city)")

let numbers = [5, 2, 8, 1, 9, 3]
let stats = calculateStats(numbers: numbers)
print("Min: \(stats.min), Max: \(stats.max), Average: \(stats.average)")

Output:

Name: Alice

Age: 28

City: New York

Min: 1, Max: 9, Average: 4.666666666666667

🔹 Optional Return Values

Functions can return optional values when they might not have a result:

// Function that might not find a result
func findFirstEven(in numbers: [Int]) -> Int? {
    for number in numbers {
        if number % 2 == 0 {
            return number
        }
    }
    return nil  // No even number found
}

func divide(a: Double, b: Double) -> Double? {
    if b == 0 {
        return nil  // Can't divide by zero
    }
    return a / b
}

// Use optional return values
let numbers = [1, 3, 7, 4, 9]
if let firstEven = findFirstEven(in: numbers) {
    print("First even number: \(firstEven)")
} else {
    print("No even numbers found")
}

if let result = divide(a: 10, b: 2) {
    print("Division result: \(result)")
} else {
    print("Cannot divide by zero")
}

Output:

First even number: 4

Division result: 5.0

🧠 Test Your Knowledge

What symbol is used to specify a return type in Swift?