Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift argument labels and keywords

Tags:

swift

I am trying to learn Swift and came across the argument labels and an online example as follows:

func setAge(for person: String, to value: Int) {
    print("\(person) is now \(value)")
}

This can be then called as:

setAge(for: "Paul", to: 40)

My question is that isn't for a Swift keyword? I am wondering whether this use of for has some hidden meaning that I am missing or just that these keywords can also be used as argument labels?

like image 947
Luca Avatar asked Jun 06 '21 11:06

Luca


People also ask

What is argument label in Swift?

The argument label is used when calling the function; each argument is written in the function call with its argument label before it. The parameter name is used in the implementation of the function. By default, parameters use their parameter name as their argument label.

What is Variadic parameters in Swift?

Variadic parameters make it possible to pass zero or more values of a specific type into a function. It can be a clean alternative for methods that often work with one element, and you don't want to create an array of components for just a single value on the implementation level.

What is Inout in Swift?

Swift inout parameter is a parameter that can be changed inside the function where it's passed into. To accept inout parameters, use the inout keyword in front of an argument. To pass a variable as an inout parameter, use the & operator in front of the parameter.

What is #function in Swift?

Advertisements. A function is a set of statements organized together to perform a specific task. A Swift 4 function can be as simple as a simple C function to as complex as an Objective C language function. It allows us to pass local and global parameter values inside the function calls.


1 Answers

or just that these keywords can also be used as argument labels?

Exactly. This is introduced in SE-0001 Allow (most) keywords as argument labels. The motivation is that:

Sometimes, the most natural label for an argument coincides with a language keyword, such as in, repeat, or defer. Such keywords should be allowed as argument labels, allowing better expression of these interfaces.

Though in SE-0001 it is said that inout, var and let are not allowed to be argument labels (back then they are used to describe the mutability of the parameter). This restriction was later relaxed. Now, only inout is not allowed as an argument label, and you get a warning if you use var or let as an argument label.

like image 199
Sweeper Avatar answered Oct 16 '22 11:10

Sweeper