Swift - Function Parameter Names

Introduction

Consider the following code:

func myFunction(num1: Int, num2: Int) {
     print(num1, num2)
}

Here, num1 and num2 are the two parameters names for the function and they can only be used internally within the function.

These are called local parameter names.

When calling this function, these two parameters names are not used at all:

myFunction(5, 6)

In more complex functions with multiple parameters, the use of each parameter is sometimes not obvious.

Therefore, it would be useful to name the parameter(s) when passing arguments to a function.

In Swift, you can assign an external parameter name to individual parameters in a function.

Consider the following example:

func myFunction(num1: Int,  secondNumm  num2: Int) {

}

Here, the second parameter is prefixed with an external parameter name secondNum.

To call the function, you now need to specify the external parameter name, like this:

myFunction(5,  secondNum : 6)

If you define a function within a class, the second parameter onwards automatically becomes an external parameter name.

There is no need to explicitly specify the external parameter names for the parameters (second parameter onwards) in the function declaration.

You can also specify an external parameter name for the first parameter, such as the following:

func myFunction( firstNumm  num1: Int, secondNum num2: Int) {
}

In this case, you need to specify external parameter names for both parameters:

myFunction(firstNum:5, secondNum:6)
func myFunction(firstNum num1: Int, secondNum num2: Int) {

External parameter names are very useful for making function names descriptive.

Related Topic