DEV Community

Maegan Wilson
Maegan Wilson

Posted on • Updated on • Originally published at Medium

Argument Labels for Functions in Swift

Functions in Swift - Argument Labels

This post is a continuation of Functions in Swift Part 1 by covering argument labels in Swift functions.

Argument labels are the parameter names that functions take in. When declaring argument labels, there are options to have them ignored or labeled as something different when calling the functions.

Omit argument labels

To omit argument labels, use a _ before the parameter name. A parameter name is still necessary to access the argument's value inside the function.

Omitting the argument label might be wanted to make the function more readable.


func addFour(_ num: Int) {
    print num + 4

addFour(2) // Prints 6
Enter fullscreen mode Exit fullscreen mode

In the example, num is not needed when calling addFour. num is used in the function body to add 4 to the integer that is passed to the function.

Specifying argument labels

To give a parameter name a different label, declare the label before the name.

func functionName(argumentName parameterName: ParameterType){
Enter fullscreen mode Exit fullscreen mode

When using the parameter inside the function, the parameter name will need to be used. This Swift feature is to make functions more sentence like. It allows for the function to be more human-readable.


var name = "Maegan"

func setName(to newName: String){
    name = newName

print(name) // Maegan

setName(to: "Thorgi")

print(name) // Thorgi
Enter fullscreen mode Exit fullscreen mode

In this example, anyone using setName can read that the name will change to the string that follows to. When working on what the function does, it is also easy to understand since the parameter name is newName.

If you enjoy my posts, please consider sharing it or Buying me a Coffee!

Buy Me A Coffee

Top comments (0)