Swiftly

Swift 5.7 references for busy coders

Functions

Functions are a special type of closures. Functions are first-class types, so a function can be passed in as a parameter to another function. Also, a function can return another function. Functions that belong to a struct, class, or enum are methods.

Function with type () -> ()

This function takes no parameters, and returns nothing.

func greet() {
  print("Hello")
}
greet() // "Hello"

Function with type (String) -> ()

This function takes one parameter, a String, and returns nothing.

func greet(person: String) {
  print("Hello \(person)")
}
greet(person: "Aliya") // "Hello Aliya"

Function with type (Int, Int) -> (Int)

This function takes two parameters, both Ints, and returns an Int.

func multiply(x: Int, y: Int) -> Int {
  return x * y
}
print(multiply(x: 5, y: 6)) // 30

Function with a default parameter value

This function takes two parameters, both Ints, and returns an Int.

func greet(person: String = "guest") {
  print("Hello \(person)")
}
greet() // Hello guest
greet(person: "Aliya") // Hello Aliya

Function that takes in another function as a parameter

The function perform has type ((Int, Int) -> Int, Int, Int) -> Int.

func multiply(x: Int, y: Int) -> Int {
  return x * y
}
func perform(fn: (Int, Int) -> Int, 
             a: Int, 
             b: Int) -> Int {
  return function(a, b)
}
let result = perform(fn: multiply, 
                     a: 5, 
                     b: 6)
print(result) // 30

Function that returns a function

The function operation has type () -> (Int, Int) -> Int.

func multiply(x: Int, y: Int) -> Int {
  return x * y
}
func operation() -> ((Int, Int) -> Int) {
  return multiply
}
let myOperation = operation()
let result = myOperation(5, 6)
print(result) // 30

Further reading