Swift allows you to use a variety of parameters with functions. So, we’ll look at default parameters in Swift in this exercise.
A real value assigns to a parameter in the function’s definition for default parameters. In the function call, a parameter with a default value does not require an argument to pass into it.
Let’s look at an example of a default parameter in action. Let’s pretend we’re writing a programme that computes the total bill amount with a 30% (0.3) discount:
func Discount(totalBill: Double, discount: Double = 0.3) -> Double {
return totalBill + (totalBill * discount) ;
}
discount
is the default parameter in the function Discount(totalBill:discount:)
.
=
) and a default value.We can omit the discount parameter entirely when calling the function, and the program will use the default value of 0.3
instead of discount in the function body:
print(Discount(totalBill: 500)) ;
// Prints: 150.0
If we want to use a different discount, such as 40% instead of 30%, we can call the function and pass in the new discount
argument:
print(Discount(totalBill: 500, discount: 0.4)) ;
// Prints: 200.0
The new discount
parameter value of 0.4
will override the default value set in the function definition and return
the result of the expression (500 * 0.4)
.
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.