Skip to Content
Learn
Functions
Default Parameters

Swift supports a number of various parameters used with functions. In this exercise, we’ll explore one of them: default parameters.

Default parameters have a real value assigned to a parameter in the function’s definition. A parameter that has a default value does not require an argument passed into it when the function is called.

Let’s see a default parameter in action. Assume we’re writing a program that calculates the total bill amount with a 20% (0.2) tip:

func totalWithTip(total: Double, tip: Double = 0.2) -> Double { return total + (total * tip) }

tip is the default parameter in the function totalWithTip(total:tip:).

  • A default parameter is set up in the same way as a regular parameter except it’s followed by an assignment operator (=) and a default value.
  • The default value should be the same data type as the parameter type.

When calling the function, we can omit the tip parameter entirely and the program will substitute the default value, 0.2, with tip in the function body:

print(totalWithTip(total: 50)) // Prints: 60.0

In the case that we want to use a different tip - say 15% instead of 20%, we can call the function and pass in the new argument for tip:

print(totalWithTip(total: 50, tip: 0.15)) // Prints: 57.5

The new value, 0.15 for the tip parameter will override the default value that was declared in the function definition and return the value of the expression, 50 + (50 * 0.15).

Instructions

1.

In Ticket.swift, write a function, bookingTicket() that will return a String containing booking information for an upcoming train trip.

bookingTicket() should accept the following parameters:

  • passengerName of type String and a default value of your name.
  • seatClass of type String and a default value of "Economy"
  • timeOfDeparture of type Int

Within the function, return the following String where the brackets are to be replaced with the correct string interpolation syntax:

[passengerName], your seat class is [seatClass], and you will be departing at [timeOfDeparture].
2.

Call the function and pass in 9 for the timeOfDeparture parameter. Don’t include any other parameters or arguments in your function call.

Wrap the function call within a print() statement.

3.

It’s the passenger’s lucky day, and they get a seat class upgrade to Business class!

On the following line, call the function passing Business for the seatClass parameter, and 9 for the timeOfDeparture parameter.

Wrap this function call in a print() statement.

Folder Icon

Take this course for free

Already have an account?