Hello Friends,
From the past few posts, we have been learning swift one step at a time. In our previous post, we completed control flow. The code for this post is available here.
Starting today next few posts will be on functions. Function definition and function call will be covered in this post. Subsequent posts will focus on parameters, return types and argument labels respectively.
So, what are functions?
Functions are self-contained blocks of code that solve a specific purpose. For example, the factorial function that you see here is used to find the factorial of a given number.
func factorial (number: Int) -> Int{ var factorial = 1 var temp = number while(temp>1){ factorial = factorial * temp temp = temp - 1 } return factorial }
Or this print that we use so much. The print is also a function which is used to print the results on the console.
How do we define functions?
We do that using the following syntax
func functionName (paramName: paramType ) -> returnType{ //block of code return object }
It is clear that the function definition can be broken down into three main parts:
- Function name through which we can call this function.
- Parameters list which is actually list of inputs for this function
- Return type which defines the type of result the function is going to return.
Let’s see this factorial function definition to better understand function definition
As we can see, the function name is defined as factorial. The parameter name is number. And the Parameter type is an integer. Return Type is also Integer. Then we have a code inside the curly brackets which calculates the factorial and stores it into a factorial variable and returns it. The data type of factorial variable is Integer, similar to the return type mentioned in the first line of the function.
How to call a function?
Now that we have defined factorial, how do we use it? How do we call it? How can we find the factorial of number 7 using this function?
The syntax for the function call is given below:
functionName(paramName: paramValue)
Like in this example we use print factorial of a number is factorial(number: 7). 7 is an integer and we have defined the parameter of the number as an integer.
print("Factorial is \(factorial(number: 7))")
In the next post, we will begin going deeper into functions.