Now that we've learned about function parameters and arguments, let's see why they are so important in our prgrammers' life:
Consider this: Three students named Andy, Mike and Sally made a mistake. And so their teacher asked each of them to write an apology on the whiteboard.
We can put the apologies in a program like this:
print("This is Andy")
print("Andy made a mistake")
print("Andy suffers the consequences")
print("This is Mike")
print("Mike made a mistake")
print("Mike suffers the consequences")
print("This is Sally")
print("Sally made a mistake")
print("Sally suffers the consequences")
That's decent. But what if we want to change the students' names?
We would have to go through the whole program and change each individual name with the new one.
And if we dealt with 10 students instead of 3 and if the apology text consisted of more than 3 lines, this would quickly get out of hand.
The story with functions:
This is where functions with parameters shine. We can write a function that takes in a student's name as argument and prints the specific aplogy for that student.
Then, we'll just call the function for each individual student:
func printMessage(name: String) {
print("This is \(name)")
print("\(name) made a mistake")
print("\(name) suffers the consequences")
}
printMessage(name: "Andy")
printMessage(name: "Mike")
printMessage(name: "Sally")
Changing the story:
Need to change the students' names? We only change the arguments in the function calls.
Need to change the aplogy text a little bit? We only change it inside the function instead of changing it in the whole program.
func printMessage(name: String) {
print("This is the apology of \(name)")
print("\(name) made a mistake and so \(name) suffers the consequences")
}
printMessage(name: "Andrei")
printMessage(name: "Paul")
printMessage(name: "Mary")
Assignment
Follow the Coding Tutorial and let's write some functions.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.