Learning Swift: Functions [Argument labels]

Learning Swift Functions Argument labels

 

From last three posts, we have been working on functions in swift. So far we learned

In this post, we will learn about function argument labels.

Recall this syntax we discussed in the first post on functions.

func functionName (paramName: paramType  ) -> returnType{
 
 //block of code
 return object
 
 }

 

Here we have not used argument labels. First, let’s add the argument labels to this syntax.

func functionName (argumentLabel paramName: paramType  ) -> returnType{
 
 //block of code
 return object
 
 }

 

What is this argument label? Why do we use it? How’s it different from the parameter names.

Let’s find out.

Remember this factorial function from last few posts?

func factorial (number: Int) -> Int{
    var factorial = 1
    var temp = number
    while(temp>1){
        factorial =  factorial * temp
        temp = temp - 1
    }
    return factorial
}

 

We will add an argument label “of” to the parameter name number.

func factorial (of number: Int) -> Int{
    var factorial = 1
    var temp = number
    while(temp>1){
        factorial =  factorial * temp
        temp = temp - 1
    }
    return factorial
}

 

Immediately we have an error here, where we are calling this function factorial.

Learning Swift Functions Argument labels example 1

The error says “Incorrect argument label in call(have number:”, expected “of:

When we replace the number with of, the error vanishes.

Learning Swift Functions Argument labels example 2

This “of’ here is an argument label. The argument labels are like external parameter name. These are used when calling a function. The other parameter name “number” is the internal parameter name and is used inside the function.

Earlier when there was no “of” ie argument label, the parameter name became the default argument label and we used “number:” instead of “of:”.

So when we explicitly write an argument label we have to use that in the function call. Else we use the parameter name as argument label.

The use of argument label makes a function more expressive, sort of like a sentence. Like this factorial function call above, now, can be read as the factorial of 7.

With this we complete functions. If you have any questions leave them in the comment section below.