Swift: Functions

Functions in Swift:

Let’s begin with functions in Swift.

Function:

A function is a named, reusable code block that performs a certain task. It has a definition with the func keyword, name, optional parameters, and return type, as well as a body with the code block needed to do its task.

func ingredients() -> Void {
  print("Egg")
  print("Butter")
  print("Breadcrumbs")
  print("Potato")
}

Calling a Function:

Calling a function is the process of executing the code included within its body. When you type a function’s name followed by a set of parentheses, (), you’re calling it, which should include any necessary arguments.

func welcomeVisitor() {
 print("Welcome to Code of code!")
}
 
// Function call: 
welcomeVisitor() // Prints: Welcome to Code of code!

Returning a Value:

Because a return statement can use to pass a value from a function. So, the return type of a function that returns a value must be specified in the function definition.

let yearOfBirth = 1998
var currentYear = 2022
 
func findAge() -> Int {
  return currentYear - yearOfBirth
}
 
print(findAge()) // Prints: 24

Multiple Parameters:

In its definition, a function can accept multiple parameters. All parameters must separate by commas and given arguments during the function call.

func fracToDecimal(numerator: Double, denominator: Double) -> Double {
  return numerator / denominator
} 
 
let decimal = fracToDecimal(numerator: 4.0, denominator: 5.0) 
print(decimal) // Prints:  0.8

Returning Multiple Values:

A tuple is a collection of values that a function returns. Each value within parentheses should be labelled and assigned a type in the function definition when a tuple is returned.

func myCar() -> (name: String, version: String, yearReleased: Int) {
  return ("Honda", "Honda Insight", 2021)
}
 
let car = myCar()
 
print(car.name) // Prints: Honda
print(car.version) // Prints: Honda Insight
print(car.yearReleased) // Prints: 2021

Omitting Argument Labels:

When a _  is prepended to a parameter in the function definition, an argument label can be omitted from the function call.

func calcDifference(_ x: Int, y: Int) -> Int {
  return x - y
}
 
print(calcDifference(10, y: 5)) // Prints: 5

Parameters and Arguments:

Between the () in a function definition are parameters, which are optional input values. For each defined parameter, a real value must pass in as an argument during the function call.

func perimeterOfSquare(side: Int) -> Int {
  return side * 4
} 
 
let perimeter = perimeterOfSquare(side: 6)
print(perimeter) // Prints: 20
 
// Parameter: side
// Argument:  6

Implicit Return:

In Swift version 5.1, implicit return introduces to reduce the amount of code in a function body. Hence a function that returns a single value or expression can use an implicit return if the return keyword is omitted.

func nextOscarAwards() -> String {
  "March 27, 2022"
}
 
print(nextOscarAwards()) // Prints: March 27, 2022

Default Parameters:

A real value can assign to a parameter in the function’s definition as a default parameter. When a function with a default parameter is called, it’s doesn’t require an argument for that parameter. So, the value of the argument will overwrite the default value if it appears in the function body.

func totalDiscount(bill: Double, discount: Double = 0.3) -> Double {
 return bill + (bill * discount) ;
}

print(totalDiscount(bill: 600)) ;
 
// Prints: 180.0

Variadic Parameters:

A variadic parameter is one that takes zero or more values of same type. Therefore, it’s specified in the function definition by three consecutive dots,, just after data type of a parameter.

func totalEmployees(employees: String...) -> Int {
  let numOfEmployees = employees.count
  return numOfEmployees
}
 
print(totalEmployees(employees: "Lily", "Carla", "Jamie", "Ceaser", "Luke" )) // Prints: 5

In-Out Parameters:

A function can reassign the value of a variable passed in as an argument to use an in-out parameter. In the function definition, an in-out parameter is denoted by inout, and when the function is called, the variable argument must be prepended with a &.


var currentPresident = "Donald J. Trump" 
 
func determinePresident(yearNum: Int, president: inout String) {
 
switch yearNum {
  case 1993...2001:
    president = "Bill Clinton?" 
  case 2001...2009:
    president = "George W. Bush"
  case 2009...2017:
    president = "Barack Obama"
  case 2017...2021: 
    president = "Donald J. Trump"
  default: 
    president = "Unknown"
  } 
} 
 
determinePresident(yearNum: 2005, president: &currentPresident)
 
print(currentPresident) // George W. Bush

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: