Swift – Call Function with no Parameter Labels
To call a function with no parameter labels in Swift, place an underscore before that parameter in the function definition.
Examples
In the following program, we will define a function that accepts a String name
, and specify this parameter name
such that the label name
is not required while calling the function.
main.swift
</>
Copy
func greet(_ name: String) {
print("Hello \(name)")
}
greet("Abc")
Output
If there are multiple parameters for a function, and if we would like only some of these parameters to be passed via function call without the need to mention the labels, place underscore only for these parameters.
main.swift
</>
Copy
func greet(_ name: String, country: String) {
print("Hello \(name)")
print("Are you from \(country)?")
}
greet("Abc", country: "Canada")
Output
Conclusion
In this Swift Tutorial, we learned how to define a function in Swift such that no label is required to specify for a parameter while calling the function.