Functions in Swift

Functions are central in Swift. We’ll learn about functions with a few different examples.

import Foundation

// Here's a function that takes two Int's and returns
// their sum as an Int.
func plus(_ a: Int, _ b: Int) -> Int {
    // Swift allows implicit returns for single-expression functions,
    // but we'll use an explicit return here for clarity.
    return a + b
}

// In Swift, you don't need to specify the type for each parameter
// if they're the same. You can group them together.
func plusPlus(_ a: Int, _ b: Int, _ c: Int) -> Int {
    return a + b + c
}

// The main functionality is typically in the top level scope in Swift,
// not wrapped in a main() function like in some other languages.
let res = plus(1, 2)
print("1+2 =", res)

let res2 = plusPlus(1, 2, 3)
print("1+2+3 =", res2)

To run this Swift code, you would typically save it in a file with a .swift extension, for example functions.swift, and then use the Swift compiler or Swift REPL:

$ swift functions.swift 
1+2 = 3
1+2+3 = 6

There are several other features to Swift functions. One is multiple return values, which we’ll look at next.

Swift has some key differences from other languages when it comes to functions:

  1. Swift uses the func keyword to declare functions.
  2. Parameter names are part of the function’s signature and are used when calling the function, unless you use an underscore _ to allow calling without an external name.
  3. The return type is specified after the -> symbol.
  4. Swift supports implicit returns for single-expression functions, though we’ve used explicit returns here for clarity.
  5. Swift doesn’t require a main() function as an entry point. Code at the top level of a file is executed when the program starts.

These examples demonstrate basic function syntax and usage in Swift, showing how to define functions with different parameters and return values, and how to call these functions.