Course

Swift Function: Syntax, Usage, and Examples

A function in Swift lets you write reusable blocks of code that perform specific tasks. You can define functions with input parameters, return values, or simply execute code without returning anything.

How to Write a Function in Swift

You define a function using the func keyword, followed by a name, optional parameters, and an optional return type.

Defining and Calling a Function

This function prints a simple greeting message when you call it.

swift
func greet() { print("Hello, Swift!") } greet() // Calls the function

Function with Parameters

You can pass values into a function to make it more flexible.

swift
func greet(name: String) { print("Hello, \(name)!") } greet(name: "Alice") // Output: Hello, Alice!

Function with Return Value

A function can return a value using the -> symbol before the return type.

swift
func add(a: Int, b: Int) -> Int { return a + b } let sum = add(a: 5, b: 3) // sum = 8

When to Use Functions in Swift

You should use functions when you want to organize, reuse, or simplify your code.

Reducing Repetitive Code

If you find yourself writing the same code multiple times, define a function instead.

swift
func printWelcomeMessage() { print("Welcome to the app!") } printWelcomeMessage() printWelcomeMessage()

Processing Data

A function lets you take input, process it, and return a result.

swift
func square(number: Int) -> Int { return number * number } let result = square(number: 4) // Output: 16

Handling Callbacks

You can use functions as callbacks to execute code when an event occurs.

swift
func fetchData(completion: () -> Void) { print("Fetching data...") completion() } fetchData { print("Data fetched successfully!") }

Examples of Functions in Swift

Using Default Parameter Values

You can set default values for parameters so they become optional when calling the function.

swift
func greet(name: String = "Guest") { print("Hello, \(name)!") } greet() // Output: Hello, Guest! greet(name: "Bob") // Output: Hello, Bob!

Returning Multiple Values with Tuples

A function can return multiple values by using a tuple.

swift
func getUser() -> (name: String, age: Int) { return ("Alice", 30) } let user = getUser() print("Name: \(user.name), Age: \(user.age)")

Passing a Function as an Argument

You can pass functions as parameters to other functions.

swift
func operateOnNumbers(a: Int, b: Int, operation: (Int, Int) -> Int) -> Int { return operation(a, b) } let result = operateOnNumbers(a: 10, b: 5, operation: { $0 - $1 }) // Output: 5

Nesting Functions

You can define functions inside other functions to keep helper logic contained.

swift
func outerFunction() { func innerFunction() { print("Inner function called!") } innerFunction() } outerFunction()

Using Functions in a Class

A class function belongs to a class and is called using the class name.

swift
class Math { class func multiply(a: Int, b: Int) -> Int { return a * b } } let product = Math.multiply(a: 3, b: 4) // Output: 12

Learn More About Functions in Swift

Functions in Swift come with advanced features like closures, generics, and different ways to pass data.

Closures vs. Functions

Closures are anonymous functions that capture surrounding variables.

swift
let multiply = { (a: Int, b: Int) -> Int in return a * b } let result = multiply(4, 5) // Output: 20

Generic Functions

Generic functions let you write flexible, type-safe code that works with different data types.

swift
func swapValues<T>(a: inout T, b: inout T) { let temp = a a = b b = temp } var x = 10, y = 20 swapValues(a: &x, b: &y) print(x, y) // Output: 20, 10

Using Functions with Structs

Functions can accept and return structs.

swift
struct User { var name: String var age: Int } func printUser(user: User) { print("User: \(user.name), Age: \(user.age)") } let user = User(name: "Alice", age: 25) printUser(user: user)

Enum Functions

Enums can contain functions to provide additional functionality.

swift
enum Direction { case north, south, east, west func description() -> String { switch self { case .north: return "Going north" case .south: return "Going south" case .east: return "Going east" case .west: return "Going west" } } } let move = Direction.east print(move.description()) // Output: Going east

Global Functions

Global functions are functions that exist outside of classes or structs and can be called from anywhere.

swift
func sayHello() { print("Hello, world!") } sayHello()

Returning a Function

A function can return another function as a result.

swift
func makeMultiplier(multiplier: Int) -> (Int) -> Int { return { number in number * multiplier } } let double = makeMultiplier(multiplier: 2) print(double(5)) // Output: 10

Best Practices for Functions in Swift

  • Use clear and descriptive names that explain what the function does.
  • Keep functions small and focused on a single task.
  • Use default parameter values to make functions more flexible.
  • Return tuples when you need to return multiple values.