Function is a set of instructions or block of code which is written to perform a task and given
a name to be identified as what it has been intended to do. Name of function is used to call it
when it is required. It could take input parameters to perform on and could return the output.
Say for example we want to write a perform a task of adding two numbers and get the result after
If you remember our first example was to print "Hello World" on console and there we used print function as above.
To define a function we need three things. First thing is name of the function and other
thing is input parameters and third one is return type. For example we want to
define a function which will add two integers. Lets name this function as add and parameters
as a and b of type Int. Below is the add function defined which takes two
Integers and returns the sum of both the Integers.
func add(let a: Int32, let b: Int32) -> Int32
We use func keyword then name of the function which is add in this case and then in brackets the input parameters which are a and b here. You can see let is written before a and b and after : [colon] type is written as Int32 to tell the compiler that a and b are immutable data of type Int32. We can have other type of parameters. You can also see after closing bracket Int32 is written after '->' which denotes that the return value of this function is of type Int32.
To call a function when we need, we simply need to call it using it's name and provide required
parameters. Also if function is returning some value then we need to hold that in suitable data
storage. Lets call our add function.
var sum = add(10, 20)