Functions In Swift Programming Language

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 is a block of code which performs the given task, whenever a code is needed at multiple places in your app. So, you can make a function and call it everytime you need that code instead of writing the complete code again and again.

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

  • You can use a function when you require to use a single task many times, without writing multiple lines of code again and again.
  • The parameters of functions are constant. So, you must change them in a variable, if you take any type of work through parameter.
  • Function can take zero parameters and multiple parameters as well.