0
0
Swiftprogramming~15 mins

Omitting argument labels with _ in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using _ to Omit Argument Labels in Swift Functions
📖 Scenario: Imagine you are creating a simple calculator app that adds two numbers. You want to make the function call easy and clean by omitting argument labels.
🎯 Goal: Build a Swift function that adds two numbers without requiring argument labels when calling it.
📋 What You'll Learn
Create a function named add that takes two Int parameters without argument labels.
Use _ to omit argument labels in the function definition.
Call the function with two numbers without labels.
Print the result of the addition.
💡 Why This Matters
🌍 Real World
Omitting argument labels makes function calls simpler and more natural, especially in small utility functions or when the meaning is clear from context.
💼 Career
Swift developers often use <code>_</code> to improve code readability and API design in iOS app development.
Progress0 / 4 steps
1
Create the add function with two parameters
Write a function named add that takes two Int parameters named a and b. For now, just return 0 inside the function.
Swift
Need a hint?

Define the function with func add(a: Int, b: Int) -> Int and return 0 for now.

2
Omit argument labels using _
Modify the add function so that both parameters a and b omit argument labels by using _ before their names.
Swift
Need a hint?

Use _ before each parameter name like func add(_ a: Int, _ b: Int) -> Int.

3
Implement addition logic inside the function
Change the add function to return the sum of a and b.
Swift
Need a hint?

Return a + b inside the function.

4
Call the function without argument labels and print the result
Call the add function with arguments 5 and 7 without labels, store the result in sum, and print sum.
Swift
Need a hint?

Call add(5, 7), assign to sum, then print sum.