Swift Programming Tutorial: Functions
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.