Introduction

The series of the articles is continuing today. This article is about functions in Swift programming language. Functions in Swift are similar to that in other languages, but there is a slight difference between Swift functions and functions in other programming languages.

What is Functions?

Function Declaration

The declaration of function is the same in Swift as in other programming languages. Here, the difference is that we give a return type after parameter brackets.

func functionname(parameter)->Return Type
{

}

Void Function

Now, we make a simple void function which can only print our name. This void function can’t return anything. Also, the benefit of function in this example can clear your concept.

code

In this image, you can see that we made a simple void function which prints single line. After that, we call our function with function name and you can see that when a function is called two times, it prints twice. Because the function is called two times. This is the feature of IDE

Code


func name()
{
print("Visual Programming")
print("Visual Programming")
print("Visual Programming")
print("Visual Programming")
print("Visual Programming")
}


name()
name()


Function Parameters

In the previous example, we saw that we made a simple void function which takes no parameters and our round brackets of function are empty. If you need to pass the parameter in function, give the name and data type in it, like this:

code

In this example, we simply make an add function which takes two parameters, adds them, and gives the result.

Code

func add(a:Int,b:Int)->Int
{
return a+b
}

add(2, b: 56)


Parameters Handling

By default, the parameters in function are constant. That means, once you declare, it can’t be changed or modified. Here, modified means like the increment in your parameter. By default, the parameters are constant.

code

In this example, you can see that we pass one parameter in a function and want increment in it, but when the value is increased, it gives an error because value parameter is treated as a constant.

code

Now, I simply add the var keyword in parameter. Then, we call the function and pass the number. Here, you can see that it works fine and shows no error.

Main points about the functions