Swift - Function Constant and Variable Parameters

Introduction

By default, all the parameters in a function are constants.

Your code within the function is not allowed to modify the parameter.

The following illustrates this:

func myFunction(num: Int) {
     num++  //this is illegal as num is a constant by default
     print(num)
}

To modify the value of a parameter, copy it out to another variable, like this:

func myFunction(num: Int) {
     var n = num
     n++
     print(n)
}

Here, the variable n is visible only within the myFunction() function.

In general, a variable's scope is limited to the function in which it is declared.

In Swift you can prefix the parameter name with the var keyword to make the parameter a variable:

func myFunction( var  num: Int) {
     num++
     print(num)
}

The parameter duplicates a copy of the argument that is passed in:

Demo

func myFunction( var  num: Int) {
     num++//www .  j a v a  2s .c o  m
     print(num)
}

var num = 8
myFunction (num)  //prints out 9
print(num)      //prints out 8; original value of 8 is unchanged

Any changes made to the variable that is passed to the function remain unchanged after the function has exited.

Related Topic