Swift: Omitting Argument Labels

Omitting Argument Labels in Swift:

In a forin loop, we’ve seen underscores used instead of a variable name when studying Swift loops. An underscore, (_), can be used in front of a parameter name in the function definition to allow omitting argument labels in the function call in Swift.

When a _ appears in front of a parameter name in the definition, the function call only needs to specify the argument value:

func functionName(_ paramName: paramType) -> returnType {
 // function body 

functionName(argument);  // function call 

Note: The _ must be at least one space ahead of the parameter name in the function definition; otherwise, the compiler will throw an error.

Take a look at the following programme, which uses each team’s final innings to determine the game’s winner:

func findWinner(_ firstInnings: Int, secondInnings: Int) -> String {
  if firstInnings > secondInnings {
   return "The winning team is Team 1.";
  } else {
   return "The winning team is Team 2."; 
print(findWinner(120, secondInnings: 102))
// Prints: The winning team is Team 1

In the preceding program:

  • The function uses an if/else statement to compare innings and determine the winner.
  • Because of the _, the first parameter is omitted from the function call, but the second parameter name must be present.

It’s important to note how removing the first argument label from the function call results in cleaner code with less repetition.

We’ve used parameter names in function calls so far in this lesson, so using an _ or omitting a parameter name is completely optional. This syntax is preferred by many developers because it:

  1. It makes it easier to read.
  2. This prevents the function call from repeating.
  3. This is similar to how functions call in other programming languages.

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: