close

An Introduction to Functions in Swift Programming Language

functions in swift programming

In Swift, functions are flexible, easy to declare, define and understand, unlike complex Objective-C-style method where we have names and argument labels for each parameter. In this article, we will see how to define and declare functions in Swift, what are “Parameters”, how to call functions later in the code, functions with the return values and nested functions. So, let’s get started.

Also Read:-  An Introduction To Protocol Oriented Programming In Swift (Part-2)

What are the Functions and Why we need them?

In programming, functions are self-contained code block generally used to perform a specific task. Each and every programming language use the concept of functions and lets you create your own custom functionality. The name of functions identify what it does. Procedures, methods, subroutines are essentially other names of function and more or less, have the same meaning for different programming languages.

We generally have either a user-defined function that is custom made as per our need or the pre-defined that is a readymade package to use them directly without writing any logic.

Benefits of using Functions in your programming

  • Functions reduce 100’s lines of code in a program thus avoiding repetitions of code.
  • Functions usually have a common structure in almost every programming language so, it is easy to understand and implement.
  • It takes in ‘0’ or more parameters as input and may or may not return a value.
  • A function is used to separate different functionalities of a program or used combined to perform more complicated tasks.
  • Writing functions for your code makes your code more readable.

Functions in Swift Programming

A function definition in any programming consists of some parts and in Swift, we have the same terminology as we have in others.

  • Function Name −  Usually a function definition starts with its name and the convention of naming depends on the functionality you are implementing. For example:- If your function defines a ‘Start Engine Process’ then the name can be kept as ‘Start Engine’

‘func’ is the keyword to start a function in Swift and then it is followed by the function name. Here we have ‘startEngine’ as our function name.

  • Parameter List − It is kind of a default value or it is like a placeholder. When a function is invoked, we pass a value as a parameter. This value is referred to as the actual parameter or argument. Parameters list can be a type, order, and a number of the parameters of a function. In swift, these are optional; that is, a function may contain no parameters.

Here, price and name are the parameters of the function ‘myFunction’.

  • Return Type − A function may return a value. Means, after execution, it can return us an integer, float, boolean or simply nothing. The ‘return’ keyword is used to return something.  As we can see in the above example that we have returned true since our function is expecting to return a boolean value.
  • Function Body − The function body contains a collection of statements that define what the function will do when called.

NOTE:- Every function in Swift has a type, consisting of the function’s parameter types and return type. You can use this type like any other type in Swift, which makes it easy to pass functions as parameters to other functions, and to return functions from functions. Functions can also be written within other functions to encapsulate useful functionality within a nested function scope.

Also Read:- What Is “Optional” In Swift Programming Language?

Calling a Function in Swift

While creating a Swift function, you give a definition of what the function has to do. To use a function and implement its functionality, you will have to call that function to perform a defined task and at a distinct time. Now, let’s write an example to implement a function and then calling it to execute itself.

Function to swap to numbers:-

So, this way you can call a function just by typing its name.

Functions with Inputs

Functions can also be modified to take values at any instance rather than hard cording the associated values. In the rounds brackets, we can pass the parameters we want. For example:-

func getItems(){ // this round brackets takes an input or you can say parameters.

}

Now, behind the scene, the parameters ‘itemName’ and ‘howMuchQuantity’ is passed to the function definition and then it gets placed to the placeholder of as written in the print statement above.

Note:-

  • Now, you can call the function as much time and can change the value of the item name and the quantity. This makes our function with less hard-coded values.
  • You can also give a default value in the parameter if you want and if a default value is defined, you can omit that parameter when calling the function.
  • We have a variadic parameter that accepts zero or more values of a specified type. We use a variadic parameter to specify that the parameter can be passed a varying number of input values when the function is called. Write variadic parameters by inserting three-period characters () after the parameter’s type name. For Example:

func solve( numbers: Double…) -> Double {

}

  • Function parameters are constant by default so try changing the value of a function parameter within the body of that function results in a compile-time error. For changing the parameters, you need to define ‘inout’ parameter before your type. For Example:

func swapNumbers (_ a: inout Int, _ b: inout Int) {

}

  • When you call the ‘inout’ defined functions then you need to use the ‘&’ sign. For Example

var a = 5

var b = 7

swapNumbers ( &a, &b)

Functions With Outputs

So far, we have seen the function that essentially just package up the definitions or the parameters but, in Swift, you can do much more than that. A function can take an input and can return an output as we saw in the first example where our code was returning a boolean. For Example:

The (->) symbol is used to return any type in the function declaration.

Note:- The return value of a function can be ignored when it is called, for example,

The first function printCount prints a string and then returns its character count as an Int. The second function WithoutCount calls the first function but ignores its return value. When the second function is called, the message is still printed by the first function, but the returned value is not used.

Functions with Multiple Return Values

A function in Swift can have multiple return values. For Example

The function, ‘heightOfPerson’ actually returns a Tuple datatype i.e min and max. You can also use optionals for the return type if you feel that the values may or may not have any value associated with them as:-

func heightOfPerson(array: [Int] -> (min:Int, max:Int)?{

}

Functions Inside Functions (Nested Functions)

Till now, we have seen the examples of functions that are the examples of global functions, which are defined at a global scope. You can also define functions inside the bodies of other functions, that we call as Nested Functions.

Nested functions are hidden from the outside world by default, but can still be called and used by their enclosing function. An enclosing function can also return one of its nested functions to allow the nested function to be used in another scope. For Example:

Source: docs.swift.org

Well, this was for today. In the next article, we will see what are Completion Handlers and how we define them with function. Do share the post so that others can reach this one.

Harshit Satyaseel

The author Harshit Satyaseel

IOS & Web application developer | Technical Writer GeeksForGeeks.org & Technotification.com. Self-learner and Tech exuberant person.

Leave a Response

This site uses Akismet to reduce spam. Learn how your comment data is processed.