0
0
Swiftprogramming~5 mins

Omitting argument labels with _ in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does using an underscore (_) before a function parameter in Swift do?
It tells Swift to omit the argument label when calling the function, so you only pass the value without naming the parameter.
Click to reveal answer
beginner
How do you define a Swift function that takes two integers without requiring argument labels when calling it?
Use underscores before both parameters like this:<br>
func add(_ a: Int, _ b: Int) -> Int { return a + b }
Click to reveal answer
intermediate
Why might you want to omit argument labels in Swift functions?
To make function calls shorter and cleaner when the meaning is clear without labels, similar to how some built-in Swift functions work.
Click to reveal answer
beginner
What happens if you omit the underscore and call a Swift function without argument labels?
Swift will give a compile-time error because it expects argument labels by default unless you use an underscore to omit them.
Click to reveal answer
beginner
Example: How do you call this function?<br>
func greet(_ name: String) { print("Hello, \(name)!") }
You call it without the argument label:<br>
greet("Alice")
<br>Not like greet(name: "Alice").
Click to reveal answer
What does the underscore (_) before a parameter name in a Swift function mean?
AThe argument label is omitted when calling the function
BThe parameter is optional
CThe parameter is a constant
DThe parameter is ignored inside the function
Given this function:<br>
func multiply(_ x: Int, y: Int) -> Int { x * y }
<br>How do you call it correctly?
Amultiply(3, y: 4)
Bmultiply(x: 3, y: 4)
Cmultiply(3, 4)
Dmultiply(x: 3, 4)
What error will you get if you call a function with argument labels omitted but the function requires them?
ARuntime error
BCompile-time error
CNo error, it works fine
DWarning only
Why might you NOT want to omit argument labels in Swift functions?
ATo reduce memory usage
BTo make the code run faster
CTo improve code readability and clarity
DTo avoid syntax errors
How do you define a function with no argument labels for all parameters?
AUse default values
BOmit parameter names entirely
CUse optional parameters
DUse _ before each parameter name
Explain how to omit argument labels in Swift functions and why you might want to do it.
Think about how you write function calls without labels.
You got /4 concepts.
    Describe what happens if you call a Swift function without argument labels when the function expects them.
    Consider Swift's strictness about argument labels.
    You got /3 concepts.