Welcome back! So far, you've learned how to define functions and use parameters in them. In this lesson, we will take it a step further and explore how to return data from functions. This will make your functions not just perform actions but also provide valuable results that you can use later in your code.
In this unit, you'll learn how to write functions that return values. Returning data allows you to create more powerful and versatile functions. For example, consider this function that calculates the travel time to reach a planet:
Swift1// Function to calculate the duration to reach a planet
2func calculateTravelTime(distance: Double, speed: Double) -> Double {
3 return distance / speed
4}
5
6let travelTime = calculateTravelTime(distance: 1.4, speed: 0.1)
7print("Travel time: \(travelTime) days")
8// Outputs: Travel time: 14.0000 days
9// Pay attention that operations with doubles are not exact
10// So it may output also Travel time: 14.000001 days
Here, the calculateTravelTime
function takes distance
and speed
as parameters and returns the travel time. You can store the returned value in a variable for later use or print it immediately, as shown.
Understanding how to return values from functions is essential for making your code more effective and reusable. When a function returns a value, you can use that result in other parts of your code, making your functions more modular and your programs more efficient. This is especially useful in complex applications where multiple functions may need to interact and share data.
Excited to see how this can make your code even more powerful? Let's dive into the practice section and start implementing these concepts together!