Consider the following Swift function and call:
func greet(_ name: String) {
print("Hello, \(name)!")
}
greet("Alice")What will this print?
func greet(_ name: String) { print("Hello, \(name)!") } greet("Alice")
Check how the underscore (_) affects the argument label when calling the function.
The underscore (_) before the parameter name means the argument label is omitted when calling the function. So, greet("Alice") works without specifying a label.
Given this Swift function:
func multiply(_ a: Int, b: Int) -> Int {
return a * b
}
multiply(a: 3, b: 4)What error will occur when compiling?
func multiply(_ a: Int, b: Int) -> Int { return a * b } multiply(a: 3, b: 4)
Look at which parameters have labels and which don't.
The first parameter uses an underscore (_) so it has no argument label. Calling with a: 3 is invalid and causes an 'Extraneous argument label' error.
Examine this Swift code:
func divide(_ numerator: Int, _ denominator: Int) -> Int {
return numerator / denominator
}
divide(numerator: 10, denominator: 2)Why does the call to divide fail?
func divide(_ numerator: Int, _ denominator: Int) -> Int { return numerator / denominator } divide(numerator: 10, denominator: 2)
Check the use of underscores (_) in the function parameters and how the function is called.
Using underscores means no argument labels are expected when calling the function. The call incorrectly uses labels, causing a compile error.
Which statement best describes the effect of using an underscore (_) before a parameter name in a Swift function?
Think about how you call functions with and without argument labels.
The underscore (_) before a parameter name means you do not write the argument label when calling the function. You just pass the value.
Analyze this Swift code:
func calculate(_ x: Int, _ y: Int, multiplier: Int) -> Int {
return (x + y) * multiplier
}
let result = calculate(2, 3, multiplier: 4)
print(result)What will be printed?
func calculate(_ x: Int, _ y: Int, multiplier: Int) -> Int { return (x + y) * multiplier } let result = calculate(2, 3, multiplier: 4) print(result)
Check which parameters require labels and which do not.
The first two parameters use underscores, so no labels are needed. The third parameter requires the label multiplier:. The call matches this, so the output is (2 + 3) * 4 = 20.