Unit 10: Parameters & Results Flashcards

1
Q

Argument

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Argument Label

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Parameter

A

used to work with an input value or values inside a function

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Return

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Side Effect

A

any work done by a function that doesn’t help create a return value | e.g., posting a number from social media online

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Functions, Revisited

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

From Specific to General

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Your Favorite Food

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Passing More Values

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Other Favorite Things

A

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”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Getting Values Back

A

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.
//:
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Giving Values Back

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Kinds of Functions

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Building Blocks

A

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. 
//:
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Naming

A

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 be getTheFirstLetter(of: "Swift")

But this new function has another problem. Learn what it is and how to fix it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Parameter Names and Argument Labels

A

On the previous page you saw how to change the definition of a function so it had a clear purpose and read like a sentence. However, doing that introduced a different problem.

func printHello(to: String) {
    print ("Hello " + to)
}
printHello(to: "Chris")

Now you have the constant name to inside the function, which doesn’t adhere to any of the rules you learned about for good names.

This problem doesn’t actually matter much for a simple function like the one above. But you’ll find it’s confusing to read longer code where to is used as a name.

To solve this problem, you can use a different name for the parameter inside the function:

func printHello(to name: String) {
    print("Hello " + name)
}
printHello(to: "Chris")
printHello(to: "Johnny")
/*:
 The parameter has been named twice. You see the first name when you call it and you use the second name inside the body of the function.

In fact, there are better words for these two names. The names you see when calling a function (and passing in one or more arguments) are called argument labels.

The names used inside the function (the values that have been received) are parameter names.

  • Experiment: Try changing the argument label and parameter name in the function above. Notice that when you change the argument label, you have to update the places where the function is called. Also notice that when you change the parameter name, you have to update the body of the function.

You may remember that the print() function doesn’t have an argument label. Find out how to do that next.

17
Q

The Argument Without a Name

A

Look at the print function:
print(“Hello”)

When you call it, it has no argument label. That’s not a problem because print(“Hello”) makes sense on its own.

Besides, it’s awkward to read print(thingToPrint: “Hello”) and thingToPrint doesn’t add any information.

The parameter in print does not have an argument label. To declare a parameter without an argument label, you use the underscore _ where the argument label would go. In Swift, the underscore means “I don’t care about this item because I’m not going to use it”.

For example:

func printHelloTo(_ name: String) {
    print("Hello " + name)
}
printHelloTo("Maya")
printHelloTo("Hiro")
//: - experiment: Call the `printHelloTo` function a few more times. Notice that the autocompletion popup shows the parameter name, not the argument label.
//: Now it’s time to summarize what you’ve learned.
//:
18
Q

Wrapup

A

In this lesson you’ve learned to supercharge your functions by letting them take in information, do things with it, and pass information out.

You’ve learned that functions should read like sentences when you call them. You’ll achieve this by carefully choosing names for your parameters and functions.

Like all computer programs, apps are built up from many functions, passing information back and forth and working with it. You now have the power to make these important building blocks.

Practice what you’ve learned with the exercises.

19
Q

Exercise: Verbing Your Noun

A

Remember back to the Functions playground when you rewrote “Row, row, row your boat”? In that playground, the functions were all very specific. To change the first line of the verse, you had to rewrite the function.

Functions that can take arguments can be much more general.

Write a function that returns a sentence like “Row, row, row your boat” when given a verb and a noun argument. The function should look like this when you call it:
 let line = openingLine(verb: "Row", noun: "Boat")
20
Q

Exercise: Using Return Values

A

You’ve learned that functions are the building blocks of programs, but so far you’ve mostly used functions one at a time. In this exercise, you’ll use the results of one function to influence the work that’s done by another.

The function impossibleBeliefsCount takes several numbers of reported unlikely incidents. It then prints the number of impossible things to be believed:

func impossibleBeliefsCount(pigsFlying: Int, frogsBecomingPrinces: Int, multipleLightningStrikes: Int) {
    let total = pigsFlying + frogsBecomingPrinces + multipleLightningStrikes
    print(total)
}
//: - callout(Exercise):Update the `impossibleBeliefsCount` function so that instead of printing the value, it returns it as an `Int`.
//:
//: `impossibleThingsPhrase` creates a phrase using string interpolation:
func impossibleThingsPhrase() -> String {
    let numberOfImpossibleThings = 10
    let meal = "teatime"
    return "Why, I've believed as many as \(numberOfImpossibleThings) before \(meal)"
}

Now you have two functions that take parameters and return values.

21
Q

Exercise: Argument Label

A

Functions and their arguments should be named so that they read like a clear instruction when they’re called. To make this easier, you can give parameters two names - an argument label to be used when calling the function and a parameter name to be used within the function’s body.

func score(reds: Int, greens: Int, golds: Int) -> Int {
    let pointsPerRed = 5
    let pointsPerGreen = 10
    let pointsPerGold = 30
    let redScore = reds * pointsPerRed
    let greenScore = greens * pointsPerGreen
    let goldScore = golds * pointsPerGold
    return redScore + greenScore + goldScore
}
let finalScore = score(reds: 5, greens: 3, golds: 3)
/*: 
 - callout(Exercise): Add an argument label to the function definition so it reads like this when you call it:\
 `let finalScore = score(withReds: 5, greens: 3, golds: 3)`
*/
22
Q

Exercise: No Argument Label

A

Some functions names are descriptive enough that they don’t need a label for their argument. To write a function that can be called with an argument only, you use _ where you’d normally specify the argument label.

The function below has an unnecessary argument label when you call it.

func holler(phrase: String) -> String {
    return "⚡️\(phrase)!!⚡️"
}

holler(phrase: “Thank you, this is very nice.”)
holler(phrase: “I’m not sure that was necessary.”)