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?
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.
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.
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.
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.
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
, ordefer
. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With