Unit 8: Constants & Variables Flashcards
Constant
an immutable identifier
declared with Let
Immutable
unchangeable/ cannot be updated
e.g., constant
Mutable
changeable
e.g., variable
Naming Things Revisited
In Naming and Identifiers you explored the importance of naming things in real life and in programming.
In code, you’ve learned how to define a name and associate a value with it by declaring a constant:
let city = “Paris”
You’ve also learned how to define a name and associate it with a list of statements by declaring a function:
func printGreeting() { let greeting = "Hello" print(greeting) } /*: You may be starting to see a pattern. A large part of programming is making up things, giving them names, and then calling those things by name to use them.
So far, you’ve used constants whenever you’ve needed to assign a value to a name. But there’s still a important unanswered question: Why are they called constants?
You may have already guessed that the name “constant” has something to do with staying the same — remaining constant — over time.
As soon as you assign the value of a constant, you can rely on the value always being the same. The value associated with that name remains constant.
There is a second way to associate a value with a name in Swift. These are called variables.
With a variable, you can update the value over time as your program runs. The value associated with the name can change — vary — over time.
In this playground, you’ll learn more about the differences between variables and constants, how to declare variables and how to decide whether to use a variable instead of a constant.
How does this all work and why is it important?
Move on to the next page to learn more.
*/
Constant and Variable
In programming, there is an important difference between names that always refer to the same value, and names where the value can change over time.
When naming things in the real world, the difference is there too, but people usually don’t notice it.
Constant
For example, think about “your birthdate”. Your birthdate will never change. No matter how young you are or how old you get, that date remains the same. Even hundreds of years from now, when people read about how you changed the world with your magnificent apps, your birthdate will remain the same.
Your birthdate is a constant. The value is set once when you are born and never changes after that. In code, you would make birthdate a constant.
Variable
Many of the names people use every day can have different values over time.
For example, think about “your favorite shirt” or other article of clothing. When you were a little kid you may have had a favorite shirt. As you got older, you outgrew it either in size or style, and now a different shirt is your favorite. In the future, you’ll probably have a different favorite shirt. You still have that name or idea of a “favorite shirt” — but the actual shirt you are referring to changes over time. In code, you’d say that favoriteShirt is a variable.
A Little of Both
You can see a little bit of both ideas of constants and variables in most kinds of team sports. There is the notion of the “home team” and “visitors”. At your school, the home team is always the same. For your school it is constant. The name or concept of the “visitors” stays the same, but the actual team changes every game. The visiting team is variable.
Think about things in life that are constants and things that are variables. Use the list below as a starting point:
Where you were born Where you live How old you are Your favorite movie How many inches are in a foot Who was the first President of the United States
Declaring Variables
Declaring a variable is almost exactly like declaring a constant. But instead of using the keyword let, you use the keyword var:
// Declaring a constant let placeOfBirth = "New Jersey"
// Declaring a variable var currentLocation = "New Jersey"
/*: Once you have declared a variable, you can assign a new value to it: */ // Assigning a new value to a variable currentLocation = "California"
/*: - experiment: Below, add a line of code that assigns a new value to `currentLocation`: */ // Assign a new value
/*: In most ways, constants and variables are the same: - Both use the same rules for names - Both associate a name with an assigned value - Both have a specific type
The difference is:
- The value of a constant cannot be changed after it is first assigned
- The value of a variable can be changed after it is first assigned
Next, learn how to work with variables. */
Working with Variables
Now that you know how to declare variables, how and when do you use them?
You use variables in places where a value in your program needs to change over time. An example of this would be the score of a game. As the player scores more points, your code would update the value of a variable keeping track of the score.
For example this variable will be assigned an initial value of zero:
var score = 0 //: If the player scores ten points, you can update the score: score = 10 //: Now the player scores another five points, so you can update the score again: score = 15 //: This is nice, but it would be nicer to use the existing value of `score` when calculating the new value. To add another five points, you can do this: score = score + 5 //: It might seem strangely circular to set a value to equal itself plus something else, as if you're both using a value and changing it in a single step, but that isn't exactly what is happening. Even though it’s a single line of code, Swift evaluates the statement in two different steps. //: //:The right hand side of the assignment is calculated first, as if it were written on its own in a playground. Just doing a calculation with a variable doesn't change its value, though: score + 5 score score + 3 score //: But when a calculation is on the right-hand side of an assignment, the variable stores the calculation's result and takes on a brand new value: score = score + 5 score = score + 3 /*: - experiment: What do you think the value of `score` would be after these lines? Try it and find out!
``` score = 5 score = score + score ``` */
//: Next, learn a shortcut for `score = score + 5`. //:
A Shortcut
You saw how to use the current value of a variable as part of updating to a new value:
// Value is initially zero var score = 0
// Take the current value of `score`, add 2, assign the result to `score` as its new value score = score + 2 /*: This type of operation happens often enough that Swift has a special operator `+=` which is a shorthand that combines addition (`+`) and assignment (`=`) into one combined operation.
The following line of code:
score = score + 2
has the same effect as:
score += 2
- experiment: Replace the line of code
score = score + 2
above using+=
instead. Note that the result in the results bar is the same. Add a few more lines of code that add more points using the+=
operator.
#### Compound Assignment The formal name for this kind of operator is a _compound assignment_ operator. The `+=` operator not only works for numbers, but anywhere you can use the addition operator `+`.
For example, this also works with strings: */ var greeting = "" greeting += "Hello" greeting += " " greeting += "World" //: - experiment: Try building up the statement “Compound assignment is useful” using compound assignment and the following constants. The first part of the statement is done for you: let word1 = "Compound" let word2 = "assignment" let word3 = "is" let word4 = "useful" let space = " "
var statement = "" statement += word1
Confusing Changes
You may have experienced the confusion that can happen when things change.
Imagine you are meeting a group of six friends at the movies at 8 p.m.
You receive a message that the plan has changed, you are now seeing a different movie at a different theater and will be meeting at 9 p.m.
A little later you receive another message that the plan has changed again. Now you are just going to hang out at your friend’s house and watch a movie there. The time is changed to 6 p.m, and you’ll order pizza.
Then you receive another message that you’re going to be at your other friend’s house, but at 6:30 p.m.
With all of these changes, how likely is it that everyone is going to end up at the right place at the right time?
Would mistakes be less likely if the plan didn’t change?
Anytime you make a change, there’s a chance that someone who relies on the information ends up using the old information and making a mistake.
The same is true in programming. If you can make something a constant, you guarantee the value will never change. There is no chance another part of your program can get out of sync or use an old value.
Sometimes you do need to use variables. Things do change in a program as it runs. In programming, something that is able to change is called mutable, based on the word mutate, which just means “to change”.
Something that is unable to be changed is called immutable. As a rule of thumb, if something doesn’t need to change, always use a constant to reduce the chance of confusion and errors.
Speaking of errors, move on to learn about a common error when working with constants and variables.
Trying to Change a Constant
What happens if you try to assign a new value to a constant?
As you can see below, this is considered an error. The error is “Cannot assign to value: ‘name’ is a ‘let’ constant”. Now that you know more about what let and constant mean, this error makes sense.
let name = "Johnny" name = "John" /*: The error in the gutter looks a little different than normal.
This is the normal error indicator:
But the indicator above is a red circle with a white dot in it:
When you see an error like that, this means Xcode has an idea how to fix the error.
Fix-it
For some errors, Xcode will suggest a change in the code that will fix the error for you. This feature is called Fix-it.
Click on the red circle with the white dot in it. There are two lines of information. The first line describes the error. The second line suggests a way to fix the error:
The suggestion is to change let
to var
, and the suggested new code is shown in the playground. Press the Enter key to accept the Fix-it, updating your code and making the error vanish.
Next, see if you should always accept a Fix-it?
*/
You Make the Choice
To a spell checker, the sentence “My deer Uncle Joe came to visit.” is a perfectly good sentence. No words are mispelled.
But your Uncle Joe probably doesn’t have four legs and antlers. You probably meant “My dear Uncle Joe…”
A spell checker can give you a correct sentence that does not say what you mean. In a similar way, a Fix-it will fix errors in your code, but the fix might not be what you meant to do.
For example, on the last page, you used a Fix-it to turn a constant into a variable.
You’ve already seen that you should only use a variable when the value absolutely needs to change over time. The Fix-it is trying to be helpful, but it could be suggesting that you make something mutable that you wanted to stay immutable.
In the example on the last page, did the value of name really need to change? A better solution might have been to just set the value of the constant to “John” in the first place:
let name = "John" /*: Always remember that Xcode is a tool that is trying to give you a helpful suggestion, but it’s just a suggestion. Don’t accept a Fix-it without taking a moment to understand the change it is making. */
Safer Code in a Varying World
Why bother with constants if you can just use variables? Aren’t variables just better, because you can change them whenever you like?
No.
Sometimes you’ll write code that’s expecting the world to be a certain way. Imagine you ask a friend what they’d like to drink, and then you start working really hard to deliver it.
var friendBeverageChoice = “coffee”
driveAcrossTown() buyACoffeeMaker() /*: Depending how long you're gone for, you have no way of knowing whether your friend will change their mind before you get back. */ friendBeverageChoice = "tea"
findCoffeeGrinder()
friendBeverageChoice = "water" friendBeverageChoice = "sparkling water" friendBeverageChoice = "plain water"
findCoffeeBeans()
driveHome()
setUpCoffeeGrinder()
friendBeverageChoice = “nothing 😴”
grindBeans()
makeFriendDrinkCoffee()
/*:
You might knock on your friend’s door now at 3 a.m. and expect them to gratefully wake up to drink your coffee, but actually your friend will be mad and you’ll be disappointed. Your friend’s desire for coffee is variable, so you can’t behave in a way that expects it to be constant.
Variables in code have exactly the same problem. If you only check their value once and then do a lot of work that depends on the value staying the same, you might end up doing work that’s unnecessary or even just plain wrong.
- callout(Experiment): Change the friendBeverageChoice
from a var
to a let
constant, and notice the errors that now pepper the page. You can make this code correct in one of two ways.\
You could keep the friendBeverageChoice
as a let
constant, and delete all the lines with assignment that change it.\
Or you could change the friendBeverageChoice
to a var
variable, and delete all the lines that you can’t be absolutely certain you still need, like setUpCoffeeGrinder()
.\
The second option doesn’t leave you with a very useful program, does it?
How can you mix together constants and variables?