Programs can manage more than one type of data and so can a function. We’ve previously only worked with one parameter per function, but Swift functions can accept multiple input values at a time separated by commas.
Take a function, for example, that determines if a race car driver can proceed to the next round of qualifications given their current performance. Since this depends on two different types of data, the driver’s speed and state of the car, we can set up multiple parameters in a function:
func didQualify(slowestDriver: Bool, retired: Bool) -> String { if slowestDriver || retired { return "Eliminated" } else { return "Qualified" } }
Let’s peak under the hood:
slowestDriver
andretired
are parameters of typeBool
within the function,didQualify(slowestDriver:retired:)
that returns aString
value.- The parameters are used in an
if
/else
statement to determine whether or not the driver continues on to the next round.
Calling the function below, we pass in true
for slowestDriver
, and false
for retired
:
print(didQualify(slowestDriver: true, retired: false))
The if
statement executes within the function with the Boolean values, and the functions returns "Eliminated"
.
Instructions
In Destination.swift, set up a function, timeToDestination()
, that will use an airplane’s speed and total distance to determine the duration of a flight.
timeToDestination()
should acceptdistance
andspeed
parameters of typeInt
.timeToDestination()
should return a value of the typeInt
.
Note: You will see an error in the terminal on the right, but it will go away in the next step when we populate the body of the function with code.
Within the function body, declare the constant, time
and use the following formula to assign it a mathematical expression that determines the length of a flight:
Following the variable declaration, return time
.
Assume the passenger is flying on a superjumbo jet - the A380 from Dubai to New York! Call the function and pass in the following information about the flight:
- The distance between Dubai and New York is
6836
miles. Pass in6836
as the argument fordistance
. - The average cruising speed is
560
miles per hour. Pass in560
as the argument forspeed
.
Wrap the function call in a print()
statement.