iOS Ref

Swift 4 guide: functions

This page has moved to swiftly.dev/functions! The archive below will not be updated.

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.

Function with type () -> ()

This function takes no parameters, and returns nothing.

func greet() {
  print("Hello")
}
greet()
// Output: "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")
// Output: "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))
// Output: "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()
greet(person: "Aliya")
// Output:
// Hello guest
// 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)
// Output: "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)
// Output: "30"

Further reading