Swift - Programming Language


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 addition.

print("Hello World")
If you remember our first example was to print "Hello World" on console and there we used print function as above.

Function Definition

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
return a+b

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.

Function Call

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)


  1. Function can be nested.
  2. Function can return another function as its value.


  1. https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html