Swift Programming Tutorial: Functions

Arc Sosangyo
2 min readSep 4, 2021
Photo by: Wes Hicks at unsplash.com

This article is part of my Swift Programming Tutorial series.

A function is a reusable code containing set of instructions that performs specific outcome. The primary goal of using a function is to avoid writing the same block of code with the same purpose multiple times. Function is also called method in object oriented programming.

In Swift, we declare functions by using func.

E.g.

func raceHobbit() {
print("The Hobbits are peaceful.")
}
raceHobbit()

The output will be:

The Hobbits are peaceful.

You can customize a function by using parameters (also known as argument).

E.g.

func raceHobbit(hobbitName: String) { 
print("The Hobbits are peaceful.")
print(hobbitName, "is a Hobbit")
}
raceHobbit(hobbitName: "Bilbo")

The output will be:

The Hobbits are peaceful. 
Bilbo is a Hobbit

There will be situations that a more readable and clear parameter is better. This is useful when you’re dealing with large amount of data. In below example, we’re going to use halfling as external parameter of hobbitName.

--

--

Arc Sosangyo

Arc is an iOS developer and app publisher, a former IT manager who transitioned to iOS engineering, and a big fan of coding, science, history, and philosophy.