Functions in Swift — Argument Labels

Jay Wilson
1 min readNov 15, 2019

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.

Example

func addFour(_ num: Int) {
print num + 4
}
addFour(2) // Prints 6

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){
// DO SOMETHING
}

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.

Example

var name = "Maegan"func setName(to newName: String){
name = newName
}
print(name) // MaegansetName(to: "Thorgi")print(name) // Thorgi

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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Jay Wilson
Jay Wilson

Written by Jay Wilson

I like to solve problems using Swift, make YouTube videos, and take photos. I also really enjoy a good cup of coffee.

No responses yet

Write a response