Swift function: What is it and how does it work?

If you are new to Swift functions and really want to dig down further information about it, congratulations, you have come to the right place. So, in this blog, ArrowHiTech will deliver for you a general overview of Swift function. Then, you will easily understand and take advantage of it effectively. What are you waiting for without exploring with us right now! 

What does Swift function mean?

As you may not know, a function is a collection of statements that work together to accomplish a specific goal. A Swift 4 function is not only as simple as a C function, but it can also be sophisticated as an Objective C language function. In fact, it enables us to pass both local and global parameter values to function calls.

Way to define Swift function 

To begin, the “func” keyword in Swift 4 will define a function. Besides, as soon as a function is newly defined, it may accept one or more values as input ‘parameters,’ processing the functions in the main body and returning the values to the functions as output ‘return types.’ 

What’s more, each function will come with a function name that describes the purpose that the function accomplishes. And, if you want to use any function, all you have to do is “call” the function’s name and  give input values (called arguments) that match the types of the function’s parameters. In particular, “tuples” are another name for function parameters.

Moreover, the arguments to a function must always be given in the same order as the function’s parameter list, and the return values must always be preceded by →. 

Coming to this syntax: 

func funcname(Parameters) -> returntype {
   Statement1
   Statement2
   ---
   Statement N
   return parameters
}

Let’s keep track of this code below

func student(name: String) -> String {
   return name
}

print(student(name: "First Program"))
print(student(name: "About Functions"))

Then, we will obtain the following output as soon as we run the above program in playground:

First Program
About Functions

Way to call a Swift function

Firstly, assume we’ve created a function called ‘display’. To display numbers, for example, intitially intitialize a function with the name ‘show’ with the parameter ‘no1’, which is an integer data type. After that, the argument ‘no1’ is then assigned to argument ‘a,’ which will point to the same data type integer. And, the function now receives the argument ‘a.’

Besides, when calls the display() function, it will save the integer value and return the integer value.

func display(no1: Int) -> Int {
   let a = no1
   return a
}

print(display(no1: 100))
print(display(no1: 200))

Then, we obtain the output below when we run the above program in playground:

How does Swift function work?

#1. Parameters and Return values

In fact, Swift 4 offers a wide range of function parameters and return values, from simple to advanced. Functions in Swift 4 can have a variety of forms, similar to those in C and Objective C.

Parameterized functions

For more details, the function’s body is accessed by giving its parameter values to it. Inside the function, we can pass single or many argument values as tuples.

func mult(no1: Int, no2: Int) -> Int {
   return no1*no2
}

print(mult(no1: 2, no2: 20))
print(mult(no1: 3, no2: 15))
print(mult(no1: 4, no2: 30))

After following program using playground above, we surely gain the result:

Function without Parameters

Not only does Swift 4 have the ability to create functions with parameters, but it also allows us to build various functions that don’t have any parameters. Let’s take a look at the Syntax below:

func funcname() -> datatype {
   return datatype
}

Here’s an example of a function that doesn’t have a parameter:

func votersname() -> String {
   return "Alice"
}
print(votersname()) 

As soon as you follow program using playground above, you will surely get the result:

Swift function

Function Swift with Return Values

Functions will return types for string, integer, and float data types. Besides, the function ‘ls’ is declared with large and small integer data types to find the largest and lowest number in a given array.

In addition, an array will initialize integer values . The array is then processed, with each value in the array being read and compared to its predecessor. The value is put in the ‘small’ argument if it is smaller than the previous one, otherwise it is stored in the ‘big’ argument, and the values are returned by invoking the function.

func ls(array: [Int]) -> (large: Int, small: Int) {
   var lar = array[0]
   var sma = array[0]

   for i in array[1..<array.count] {
      if i < sma {
         sma = i
      } else if i > lar {
         lar = i
      }
   }
   return (lar, sma)
}

let num = ls(array: [40,12,-5,78,98])
print("Largest number is: \(num.large) and smallest number is: \(num.small)")

Let’s refer the result below:

Largest number is: 98 and smallest number is: -5

How about Function Swift without Return Values? 

In reality, some functions may have arguments stated within them but no return values. The sum() function is called with the arguments a and b in the following program. The values for arguments a and b are supplied inside the function by running the sum() function, whose values are reported, obviating the need for return values.

func sum(a: Int, b: Int) {
   let a = a + b
   let b = a - b
   print(a, b)
}

sum(a: 20, b: 10)
sum(a: 40, b: 10)
sum(a: 24, b: 6)

Let’s examine the outcome below:

Swift function result

#2. Swift Function with Optional Return Types

As you may know, Swift 4 adds an ‘optional’ feature to solve problems by adding a safety measure. Also, let’s consider the case when we declare the return type of a function to be integer, but what happens if the function returns a string value or a nil value. In that situation, the compiler will give you an error message. Then, to solve these issues, create ‘optional’.

Besides, optional functions provide two forms including ‘value’ and a ‘nil’. To verify whether the tuple returns a value or a nil value, we’ll mention ‘Optionals’ with the key reserved character ‘?’.

func minMax(array: [Int]) -> (min: Int, max: Int)? {
   if array.isEmpty { return nil }
   var currentMin = array[0]
   var currentMax = array[0]
   
   for value in array[1..<array.count] {
      if value < currentMin {
         currentMin = value
      } else if value > currentMax {
         currentMax = value
      }
   }
   return (currentMin, currentMax)
}

if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) {
   print("min is \(bounds.min) and max is \(bounds.max)")
}

Run as above and you will get the following outcome:

min is -6 and max is 109

#3. Swift Function Local Vs External Parameter Names

  • Local Parameter Names

The names of local parameters are only available within the function.

func sample(number: Int) {
   print(number)
}

Following the below statement:

func sample(number: Int) {
   print(number)
}

sample(number: 1)
sample(number: 2)
sample(number: 3)

And, the below thing as a great result: 

result of swift function Local Parameter Names
  • External Parameter Names

With External Parameter Names, you can call a function by naming two parameters and then calling it as below syntax:

func pow(firstArg a: Int, secondArg b: Int) -> Int {
   var res = a
   for _ in 1..<b {
      res = res * a
   }
   print(res)
   return res
}

pow(firstArg:5, secondArg:3)

Hence, you will get the awesome outcome like:

code of swift function

#4. Variadic Parameters of Swift function

Now, let’s refer to the following statement and you will understand its operating process: 

func vari<N>(members: N...){
   for i in members {
      print(i)
   }
}

vari(members: 4,3,5)
vari(members: 4.5, 3.1, 5.6)
vari(members: "Swift 4", "Enumerations", "Closures")

And, the result is:

Variadic Parameters

#5. Constant, Variable and I/O Parameters

In fact, I/O parameters in Swift 4 allow you to keep the value of a parameter even if the value changes after the function call. What’s more, the ‘inout’ keyword is specified at the start of the function parameter specification to keep the values of member. 

In terms of Variables, the in-out parameter only uses this Swift function as an argument. Besides, since both inside and outside of functions change their values. As a result, no strings or literals need to be declared as in-out parameters. Moreover, the ‘&’ before a variable name indicates that the argument is being passed to the in-out parameter.

func vari<N>(members: N...){
   for i in members {
      print(i)
   }
}

vari(members: 4,3,5)
vari(members: 4.5, 3.1, 5.6)
vari(members: "Swift 4", "Enumerations", "Closures")

Then, if you’re running the above program, the result returns will be:

swift function

In conclusion

Above all, can you share with ArrowHiTech what you think after reading this blog? Is it useful and beneficial for you? We hope you will say YES and it will be a great motivation for us to create other better articles. 

In addition, in case you have trouble working with Swift functions, let ArrowHiTech know. With many experiences in Swift and Objective-C IOS App Development Services, we are always ready to help you resolve them quickly. 

Tags

Share