Unit 10: Parameters & Results Flashcards
Argument
used to give an input value, or values, to a function; commonly refers to a function’s inputs from a perspective outside of the function (e.g., drawLine (from: startPoint, to: endPoint) | arguments: startPoint & endPoint)
Argument Label
introduces the argument passed into the function, similar to how you might write your name (“Maya”) next to a name label (“Name”) on a form (e.g., func drawLine (from fromPoint: Point, to toPoint: Point) | from & to
Parameter
used to work with an input value or values inside a function
Return
returns something when it gives an output value back to its caller; RETURN keyword marks the value that will be passed back to the place where the function was called
Side Effect
any work done by a function that doesn’t help create a return value | e.g., posting a number from social media online
Functions, Revisited
When you learned about functions, you called them like this:
doSomething()
You may have noticed that you were also calling a function in a slightly different way:
print(“Hello, world!”)
For the function print() to work, it has to have a value inside the parentheses. Without being able to pass in that value, print() wouldn’t know what to print and would be pretty useless.
Next, learn about passing values into your own functions.
From Specific to General
Do you remember how to declare and call a function? Here’s a quick refresher. Open the console to see the output:
func helloJohnny() { let name = "Johnny" print("Hello " + name) } helloJohnny() /*: The function `helloJohnny()` is very _specific_. If you wanted to say hello to Vikram, you'd need to write a `helloVikram()` function. That would soon get tedious, and programmers don’t like to repeat themselves or do more work than is absolutely necessary.
Instead of writing multiple specific functions to say hello to every possible name, you can do something more powerful and much less repetitive. You can write one general function that knows it needs a name but doesn’t know yet what that name will be.
To do that, the declaration is different. Inside the parentheses you add a name and a type annotation in the same format as when you declare a variable or constant with a type annotation. */ func hello(name: String) { print("Hello " + name) } /*: Inside the body of the function, `name` can be used just like the constant in `helloJohnny()` above.
The hello
function can now be said to have a parameter, called name
, of type String
.
Later, when someone uses the function, they can tell the function what the value of the `name` parameter should be. This is called _passing in a value_. The value you pass in to the function is called the _argument_. */ hello(name: "Maria") hello(name: "Vikram")
//: - experiment: Call the function a few more times, passing in different arguments. Notice that the autocompletion pop up tells you that the function has a String
parameter called name
.
//: Next get some practice by making your own function that takes an argument.
Your Favorite Food
The following code prints the value of a constant to the console:
let favoriteFood = "cheese" print("My favorite food is " + favoriteFood)
Put the print statement above inside a function that allows you to pass in any string as an argument. When you call the function, it should look like this:
printFavorite(food: “cheese”)
Hint: You can go back to the previous page to check on how to define a function with a parameter.
Passing More Values
What if you wanted your function to take more than one value? No problem. Just list the parameters inside the parentheses with a comma between them:
func hello(firstName: String, lastName: String) { print("Hello \(firstName) \(lastName)") } /*: It can take some practice to read these parameter lists smoothly. Remember that each parameter is a pair of one name and one type and that the commas separate each parameter. You might even picture this parameter list as:
firstName: String,
\
lastName: String
Inside the function, `firstName` and `lastName` are both available as constant strings. You can call the function like this: */ hello(firstName: "Johnny", lastName: "Appleseed") hello(firstName: "John", lastName: "Snow") //: - Experiment: Call the function a few more times with the names of your favorite celebrities. Note how autocompletion tells you about both parameters and how you can use the Tab key to move to the next argument.
//: Get some more practice with this sort of function on the next page.
Other Favorite Things
The favorite food function you created earlier is OK but perhaps a bit limited. What if you have a favorite animal or a favorite color? The following code is a more flexible version:
let categoryOfThing = "food" let favorite = "cheese" print("My favorite \(categoryOfThing) is \(favorite)")
Put the print statement above inside a function that allows you to pass in one string for the category of thing, and another string for your favorite. When you call the function, it should look like this:
printFavorite(categoryOfThing: “food”, favorite: “cheese”)
Getting Values Back
In addition to using values that you’ve passed in, functions can do their work and hand you back a value as a result.
Passing a value back when a function is finished is called returning a value. To declare a function that returns a value, you have to add two things to your code.
After your list of parameters, add a text arrow -> and the type of value to be returned. For example: -> String means the function returns a String.
Then you have to end the body of the function with a return statement that gives that type of value back.
Here’s a function that takes some numbers, does some work, and returns a string:
func spaceAvailableMessage(eachVideoDuration: Int, numberOfVideos: Int) -> String { let currentSpace = 10000 let megabytesPerVideoSecond = 3 let spaceAvailable = currentSpace - eachVideoDuration * numberOfVideos * megabytesPerVideoSecond
return "If your \(numberOfVideos) videos are \(eachVideoDuration) seconds each, you'll have \(spaceAvailable) MBs remaining" } spaceAvailableMessage(eachVideoDuration: 10, numberOfVideos: 50) //: > Your function can have multiple parameters, but it can only return **one** value. //: //: The value that a function returns is just like any other. It can be assigned to a variable or a constant and can be used for other work. Variables and constants can also be used as the arguments: let desiredVideoDuration = 40 let holidayVideoCount = 100 let videoMessage = spaceAvailableMessage(eachVideoDuration: desiredVideoDuration, numberOfVideos: holidayVideoCount) let namedVideoMessage = "Hey Micah! \(videoMessage)"
//: Try making your own function that returns a value. //:
Giving Values Back
Over the last few exercises you’ve developed a function that builds a sentence about your favorite thing and then prints the result to the console.
Building the sentence and printing it are actually two separate jobs. There could be cases when you want to build the sentence but not print it to the console. You may want to do further work on the sentence or display it on the screen.
Write a function that takes the categoryOfThing and favorite as arguments, and returns a String. You should be able to call the function like this:
let sentence = makeFavorite(categoryOfThing: “food”, favorite: “cheese”)
sentence should then have the value “My favorite food is cheese”.
Remember that -> is used to say that a function returns a value.
Call your new function a few times with some different categories, assigning each result to a different constant. Why not try categories like food, movie, school subject or band?
Next, learn when to use parameters and return values and when not to.
Kinds of Functions
When you write functions, you now have four possible combinations of parameters and return values. Here’s a summary that describes when you might use each type of function:
❌ Parameters, ❌ Return value
paintAndHangPicture()
When you call a function that doesn’t have any parameters and doesn’t return a value, it’s like saying “I want something to happen, but I don’t particularly care how it’s done or what happens to it later.”
Imagine you ask an artist to create a painting for you. If you use a function like paintPicture(), the artist will create whatever they want, then permanently hang the finished piece on whichever wall they like, maybe even in another city.
Calling this kind of function can save you the work of making decisions but can also require a lot of trust. The function does the work on its own and doesn’t give back any information, but it might have an impact on something that you have no control over.
The BoogieBot dance moves are an example of this type of function. The function name tells BoogieBot which move to do. The “work” is the move itself.
✅ Parameters, ❌ Return value
paintAndHangPicture(width: Int, height: Int, dominantColor: UIColor)
These functions do work that changes depending on the arguments, but don’t give anything back.
Now you can ask the artist to make a painting of a certain size, perhaps using a particular color scheme or featuring your favorite scenery. You take more control of the work performed, but the artist still has full control over the painting, and will hang it wherever they like.
The hello(name:) function is an example of this. You control the names, and the “work” is printing the string to the console.
❌ Parameters, ✅ Return value
paintPicture() -> Painting
This kind of function returns a value without needing any extra information.
Imagine that you haven’t given the artist any input parameters, so they create something entirely from their own vision. After they’re done with the work, they’ll hand the finished painting over to you directly. Now you can hang, sell, or maybe even add to the painting yourself.
So far in this course, you haven‘t seen a function with this combination. Examples might be functions that give you a random number or tell you the current date and time.
✅ Parameters, ✅ return value
paintPicture(width: Int, height: Int, dominantColor: UIColor) -> Painting
This kind of function gives a value back based on the information passed in. It takes all your input suggestions and transforms them into a new output value.
In this case, you give the artist input about what you’d like them to create and are handed back a finished product that you can use exactly as you like.
The spaceAvailableMessage(eachVideoDuration:, numberOfVideos:) function is an example of this type of function.
When a function does some kind of work that’s unrelated to a return value, like printing to the console, or making BoogieBot dance, the work is called a side effect. When you name a function, it’s good to somehow include the side effect in the name, like leftArmUp(). If a function has no return value, all of its work is considered a side effect. That’s why the functions that don’t return a value on this page are named paintAndHangPicture.
On the next page learn how functions can make tasks easier to understand.
Building Blocks
When you were first introduced to functions it was as a way of grouping tasks together. Each function was a building block for a larger program.
Now you’ve learned that functions can also:
Take information in
Do work
Return information
Building blocks like this are much more powerful.
This function can be used to build a list:
func listByAdding(item: String, toList: String) -> String { return toList + "\n" + item } var list = "Milk" list = listByAdding(item:"Eggs", toList: list) list = listByAdding(item:"Bread", toList: list) //: Compare this to the way you were building lists before, with compound assignment: list += "\n" + "Rice" //: You’ll probably notice that the function is easier to read,. You no longer have to use `"\n"` to separate the items in the list. _Hiding complexity_ is one of the key benefits that using functions brings to your code. //: //: Doing a good job of naming your functions and parameters will also make the work they do easier to understand. Learn about this next. //:
Naming
The function you defined early on in this playground was called like this:
hello(name: “Maya”)
But there are two problems with this function:
The function has a side effect (the name is printed to the console) but this isn’t clear from the name. A function that has a side effect should have a verb in the name.
Functions in Swift should read as much like a sentence as possible. “Hello name Maya” is not a sentence.
To address the first problem, the function could be renamed. A better name would be printHello. But the function-as-a-sentence would still read “Print hello name Maya”, which still doesn’t work. “Print hello to Maya” would be better:
func printHello(to: String) { print ("Hello " + to) } printHello(to: "Maya") /*: This function passes the side effect test and the function-as-a-sentence test.
- Experiment: Think of some more tasks a program might perform. Write them out as sentences, then think about how those sentences would look as functions.\
For example: “Get the first letter of ‘Swift’” would begetTheFirstLetter(of: "Swift")
But this new function has another problem. Learn what it is and how to fix it.