Reputation: 331
how to use underscore parameter
func test(currentName name: String, _: Int) {
print("aa\(name) abc");
//how to use _ parameter?
}
test(currentName:"aa", 3)
Upvotes: 2
Views: 922
Reputation: 7344
If you want to use second parameter of function but don't want to "name" it, you have to change signature of function to func test(currentName name: String, age _: Int)
and then refer to second argument as age
.
func test(currentName name: String, _ age: Int) {
print("Name: \(name), age: \(age)")
}
test(name: "Piter", 3)
Upvotes: 1
Reputation: 1743
In Swift, functions have both parameter labels and parameter names. This is for clarity when using the functions. Think about a normal C function, it is declared as such:
string FunctionName(string firstName, string lastName)
Looking at the function declaration, it's easy to see what each parameter is. In this case, a firstName and a lastName. However when it is called in code, it's less apparent, particularly if the parameter values aren't self-describing. eg:
FunctionName("Neil","Armstrong") // Fairly obvious
FunctionName("Bo","Ng") // Not so obvious
In swift, parameters have both labels and names. Labels are there purely for clarity, so the code that calls the function can be read and understood more easily, without having to dive into its definition to fully understand it
let fullName = funcName(firstName: "Bo", lastName: "Ng")
In some cases, the parameter name is entirely unnecessary, eg:
let total = addTwoNumbers(1,2)
So the labels are optional, denoted by an underscore
func addTwoNumbers(_ firstVal:Int,_ secondVal:Int)
Generally speaking, you should use labels to make the functions you write clearer, unless you feel the parameters are entirely self-describing.
Upvotes: 3
Reputation: 11702
_
means when you call test
function, you don't have to write the text before the second parameter test(currentName:"aa", 3)
if you declare your function like this:
func test(currentName name: String, secondParameter: Int) {
print("aa\(name) abc");
//how to use _ parameter?
}
then when you call test
function, you must to call like this:
test(currentName:"aa", secondParameter: 3)
Upvotes: 2