Swift Function

Method/Function are combinations of statements which are used to solve specific task. Function are reliable to combine group of single as well as multiple statements. The advantage of function it will be define only once. And that can be used in a so many times of during program execution. This process is provides re-usablity of codes.

Define Function

func are used to define swift function. After the name of function, within the parenthesis provide the parameters of function that is an optional when function are not accept any value. -> is an optional when function is returning any value. Finally curly braces are used to define body of function. Inside of braces can provide your logic and instructions. There of Syntax are as follows.

 func functionName(var1:Type1,var2:Type2,...)->returnType {
//body of this function
//include logic here
}

Function definition is described the behaviour of function. Such as how many number of parameter that are accepted and what is the data type, What type value are return back And function identifier name (function name).

For Example

/*
* Function : sum
* Parm     : Two integers values
*@return   : Sum of two integers
*/
func sum(num1:Int,num2:Int)->Int{
  return num1+num2
}
//result variable are use store returning value by sum function
//Provide value by parameter level
var result:Int=sum(num1:3,num2:4) //call function sum
print("Result : \(result)") //display result

Output

Result : 7

Function calling is an function execution process. When we are called user defined function then by default need to label of function parameter. In this situation there are two possibility, remove level naming by _. Or provide new custom name.

//Define custom label

func myTest(t1 test1:String,t2 test2:String){
  print(test1)
  print(test2)
}
myTest(t1:"Test Case 1", t2:"Test Case 2")

Output

Test Case 1
Test Case 2

In this case t1 and t2 are set define by custom label. But note that t1 and t2 label can't replace by variable name. Inside of function.

And underscore are used to remove default and custom label. See this example.

//Remove default and custom label

func myTest(_ test1:String,_ test2:String){
  print(test1)
  print(test2)
}
myTest("Test Case 1", "Test Case 2")

Output

Test Case 1
Test Case 2

Use label or not use but function argument provide must be in a sequence of a parameter list. If there is mis-match by label or data type then compiler are produced error. See this example.

func myTest(t1 test1:String,t2 test2:String){
  print(test1)
  print(test2)
}
//providing label-data in unordered sequence
myTest(t2:"Blood Test", t1:"X-rays Test")

Error

test.swift:6:25: error: argument 't1' must precede argument 't2'
myTest(t2:"Blood Test", t1:"X-rays Test")
       ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~
       t1:"X-rays Test",  

So avoid of this situation provide parameter list in a valid sequence.

Swift Function Categories

Behaviour of function means how many possible way to use function within our program. There categories are depending upon function parameter list and function returning values.

Function Without Arguments

This function are written by program when function are no need to get any parameter values. Generally that function are used to return some value and display result of calculation.

func message(){
  //display welcome message
  print("Welcome to swift programming")
}
message()
Welcome to swift programming

Function With Arguments

Function argument are useful when function are need to perform some operation by using parameter values. Function operations are depends to parameter values. That are providing dynamic environment. When passing new value to function parameter value. In this situation there is possible to produce new result using of parameter value.

func say(about:String){
  //Display message
  print("Hello \(about) !") 

}
say(about:"Programmer")
say(about:"Doctor")

Output

Hello Programmer !
Hello Doctor !

Function Without Returning

Some of case, we are define a function that are perform some operation and not returning any values. For example in class constructor are used to set initial value to class properties that is not returning values. Similarly some of situation function are used to display result and also set value to global or class variable. But there is not returning any value.

func printMessage(_ myMessage:String){

  print(" \(myMessage)")
  
}
printMessage("Hello XYZ")
printMessage("Are you programmer?")

Output

 Hello XYZ
 Are you programmer?

Function With Returning

In swift programming there are possible to return single and multiple values by function. That is depending upon situations. For example calculating the factorial number using of recursion.

//Calculate factorial of given number
func factorial(_ num:Int)->Int{
  if(num<=1){
    return 1
  } 
  else{
    return factorial(num-1)*num
  }
}
var number=4
print("Factorial of \(number) : \(factorial(number))")

Output

Factorial of 4 : 24

In this example are returning one integer value by factorial function when its call. If In case we are need returning more than one value by function. Then we can define a return statement which are returning more than one value. See this example

/*
* func:  separateEvenOdd
*   parm:  One integer array
* return : Two integer arrays
*/
func separateEvenOdd(data:[Int])->(even:[Int],odd:[Int]){
  //make empty array
  var evenElement=[Int]()
  var oddElement=[Int]()
  for element in data{
    if(element%2==0){
      //Even element
      evenElement.append(element)
    }else{
      //when Odd array element
      oddElement.append(element)
    }
  }
  return (evenElement,oddElement)
}

let myElement=separateEvenOdd(data:[1,2,3,4,5,6,7,8,12])

print("Returning values :\(myElement)")
print("Even Number : \(myElement.even)")
print("Odd Number  : \(myElement.odd)")

Output

Returning values :(even: [2, 4, 6, 8, 12], odd: [1, 3, 5, 7])
Even Number : [2, 4, 6, 8, 12]
Odd Number  : [1, 3, 5, 7]

In this example function are returning an tuple, which are contain two integer arrays. See one more example to return an array of integer.

func getData() -> ([Int]){
    
    var testResult = [Int]()
    //Add element
    testResult.append(1)
    testResult.append(12)
    testResult.append(32)
    return testResult
}

print(getData()) //Display result

Output

[1, 12, 32]

Function With Default Parameter

Default argument are used to when given argument are not compulsory. In this situation we can set default value to function argument. This default value are assigned to parameter when function calling process are not provide that value.

func addThreeIntegers(_ a:Int,_ b:Int=0,_ c:Int=2){
  print("Value a: \(a) b:\(b)  c:\(c)")
  let result=a+b+c
  print("Sum of [\(a)+\(b)+\(c)] are : \(result)")
}

//passing all parameter value
addThreeIntegers(1,2,3)

//passing two parameter value
addThreeIntegers(4,5)

//passing one parameter value
addThreeIntegers(1)

Output

Value a: 1 b:2  c:3
Sum of [1+2+3] are : 6
Value a: 4 b:5  c:2
Sum of [4+5+2] are : 11
Value a: 1 b:0  c:2
Sum of [1+0+2] are : 3

This example are capable to work on three different situation. This are work on single parameter value, two parameter value and three parameter value.

Note that parameter list value will assign from left to right in a sequence. So set a default values form right to left in a sequence.

Function Variadic Parameters

This type of function are capable to work on a any kind of parameter list which is combination of similar type of elements. For example we are write a function that are accept any number parameter their type are integers and that are returning the sum of all Odd numbers.

/*
* func : sumOfOdd
* parm : Variable length arguments
* return : One integers
*/
func sumOfOdd(_ elements:Int ...)->Int{
  var result:Int = 0

  for item in elements{
    if(item%2==0){
      result+=item
    }
  }
  return result
}

print("Case 1  : \(sumOfOdd(1,2,3,5,6))") //Works with 5 argument

print("Case 2  : \(sumOfOdd(1,2,3))") //Works with 3 argument

print("Case 3  : \(sumOfOdd())") //Works with zero argument

Output

Case 1  : 8
Case 2  : 2
Case 3  : 0

variadic parameter are create an array of given argument values. In case not passed any argument value then that is create an empty array.

Function In-Out Parameters

Function parameter list variables are by default constant, That is cannot be normally to modified within function execution. But in case we are need to modified that value (like mutable variable). Then we are add (prepend) inout keyword before define data type of variables.

func changeValue(_ data: inout Int){
  //modified data value
  if(data>50){
    data=50+10
  }else{
    data=50+20;
  }
}
var info=59
print("Before Change: \(info)")
changeValue(&info) 
print("After Change: \(info)")

Output

Before Change: 59
After Change: 60

In this case we are cannot pass constant or literal value to function argument. In this case Using of (&) are indicates passing argument are possible to modified inside of function execution. That is very similar to pointer in C programming.

Nested Function

Defining of function inside another function that is called nested functions. That is commonly used when solve complex problem and protect outside of outer function. Declare nested function as following syntax.

func outerWar(){
  //statements and variable of outer function
  func innerWar(){
    //statements and variable of inner function
  }
  //Remaining statements
}

That is very simple case when there is no parameters and return type of function. We can set parameters and return type in nested function using of our requirements. For example

func outerWar(_ status:Int)->Int{
    //outer function variable
  var commando:Int=0


  func innerWar(){
    print("Active inner War stategory")
    commando=10000
  }

    if status>=1 {
    innerWar()
  }
  return commando

}
var soldier=outerWar(1)

print("Ready soldier : \(soldier)")

Output

Active inner War stategory
Ready soldier : 10000

Note that in this example inner function are using the variable of outer function.

Access Inner function

Directly not accessible of inner function. But it is possible to used by reference of outer function.


func bookRecords()->((String)->String){
  
  var bookList=[
  "programming":"C++,Java,Python,C#",
  "novels":"Coffee Days, Champagne Nights and Other Secrets"
  ]
  func bookReference(_ type:String)->(String){
    var result:String="No Record"
    for (key,value) in bookList{
      if(key==type){
        result=value
        break
      }
    }
    return result
  }
  return bookReference
}
var reference=bookRecords()
var myBook=reference("programming")
print("My Book : \(myBook)")

Output

My Book : C++,Java,Python,C#

Deferring Execution

defer statement are normally use to within the function. It can be define any where within the function. But only executes at the end of function execution.

func testOperation(_ data:Int){

    defer{
        print("End of function execution\n")
    }
    if(data==0){

        print("We are go to return")
        return
    }
    print("Data value is : \(data)")
}
testOperation(1)
testOperation(0)

Output

Data value is : 1
End of function execution

We are go to return
End of function execution

Note that in this example defer statement execute when function are end all execution. This statement also work after the return statement. We can use any number of defer statement in single function. In this situation defer statement are executed in a sequence of stack propertie (last in first out). Let see this example.

func testOperation(_ data:Int){
    //first defer statement
    defer{
        print("Test 1\n")
    }
    //second defer statement
    defer{
        print("Test 2")
    }
    if(data==0){

        print("We are go to return")
        return
    }
    print("Data value is : \(data)")
}
testOperation(1)
testOperation(0)

Output

Data value is : 1
Test 2
Test 1

We are go to return
Test 2
Test 1

Returning function type of function

func average(_ data : [Int]) -> Int{
    
    if data.isEmpty{
        return 0
    }
    var result=0
    for i in data{
        result+=i
    }
    return result/data.count
}

func minElement(_ data : [Int]) -> Int{
    if data.isEmpty{
        return 0
    }
    var minValue = data[0]
    for i in data{
        if(i<minValue){
            minValue=i
        }
    }
    return minValue
}
func maxElement(_ data : [Int]) -> Int{
    if data.isEmpty{
        return 0
    }
    var maxValue = data[0]
    for i in data{
        if(i>maxValue){
            maxValue=i
        }
    }
    return maxValue
}
//Return the reference of function
func operation(_ option : Int)->([Int])->Int{

    switch(option){

        case 1:
            return average
        case 2:
            return minElement
        default:
            return maxElement   
    }
    
}

let element=[12,2,3,4]

var action=operation(1)

print(type(of:action))

var result=action(element) //execute average function
print(result)

action=operation(2)

result=action(element) //execute minElement function
print(result)


action=operation(3)

result=action(element) //execute maxElement function
print(result)

Output

(Array<Int>) -> Int
5
2
12


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved