Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Declare Functions in Swift
Written by Team Kodeco

In Swift, a function is a block of code that performs a specific task. Functions can optionally take input parameters and/or return a value.

To declare a function in Swift, use the func keyword followed by the function name, a set of parentheses and a set of curly braces. Within the curly braces, you can write the code that the function should execute. Here’s an example:

// Declare a function named greet
func greet() {
  print("Hello, World!")
}

In this example, the function greet() takes no parameters and returns no value. You can call this function by writing its name followed by parentheses:

greet() // prints "Hello, World!"

Declaring a Function that Takes Parameters

It’s possible to add parameters to a function by writing the parameter name, a colon and the parameter type within the parentheses.

// Declare a function named greet with a parameter name
func greet(name: String) {
  print("Hello, \(name)!")
}

In this example, the function greet(name:) takes one parameter of type String and returns no value. You can call this function by passing a string as an argument:

greet(name: "John") // prints "Hello, John!"

If you want multiple parameters, simply separate them with commas like so:

func greet(greeting: String, name: String) {
  print("\(greeting), \(name)!")
}

greet(greeting: "Salutations", name: "Ray") // Prints "Salutations, Ray!"

Declare a Function that Returns a Value

A function can return a value by using the -> operator followed by the return type.

// Declare a function named square that takes an integer and returns its square
func square(number: Int) -> Int {
  return number * number
}

In this example, the function square(number:) takes one parameter of type Int and returns an Int value. You can call this function by passing an integer as an argument and store the returned value in a variable:

let result = square(number: 5)
print(result) // prints 25
© 2024 Kodeco Inc.