Unit 3: Strings Flashcards
Character
a single letter, number, punctuation mark, symbol or blank space
Escape character
\ -> avoids the normal behaviour of a string
Escape sequence
combines an escape character with another character or characters to achieve a new effect;
e.g.,
(\t) -> tab
(\n) -> new line
e.g.,
“Happy birthday, dear \ (name)”
Quick Look Button
an icon that resembles a small eye that gives users a sneak peek w/ more detail
String
text value
String interpolation
used when you’d like to place the value of a constant in the middle of a string literal
you add placeholders for constants or variables with an escape sequence that puts parentheses around the code to be replaced
e.g.,
“friendName = Lee”
“Have a good one, \ (friendName)”
=
“Have a good one, Lee”
Unicode
a character representation standard for any language
String
A text value
Characters
Of course, text can contain more than just letters: There are punctuation marks, numbers, symbols, even spaces. All of these things are known as characters, and strings are made up of characters.
Letters are characters:
Aa Bb Cc Dd Ee
So are punctuation marks:
! ? . , ; :
Numbers:
1 2 3 4 5 6 7 8 9 0
Symbols:
@ $ & © π * + - /
Even invisible characters like spaces and tabs:
(You can’t see them, but they’re there.)
Defining Strings
In the previous playground, you declared number constants like this:
let heightInCentimeters = 7817 //: To declare a string constant, you put text between quotation marks like this: let favoriteBook = "The Sun Also Rises"
let traditionalGreeting = "Hello, world!" //: The declared string values also appear in the results sidebar. 👉 //: - experiment: Practice by declaring `favoriteMovie` and `favoriteSong` string constants for your favorite movie and song: // Declare a favoriteMovie constant
// Declare a favoriteSong constant
Unicode
an international standard that can represent almost any character from any language in a standard way
Full
Strings in Swift are fully Unicode-compliant, so you can create strings that contain the text of different languages:
let englishGreeting = “Hello, World!”
let chineseGreeting = “你好,世界!”
let spanishGreeting = “¡Hola Mundo!”
let russianGreeting = “Привет мир!”
let japaneseGreeting = “こんにちは世界!”
//: Strings in different languages let you create apps that can be used by people around the world.
//:
//: Of course, programmers around the world speak different languages. In Swift, you can use Unicode in names:
// Constant name in Chinese that means ‘English Greeting’
let 英语问候 = “Hello, World!”
// Constant name in French that means 'English Greeting' let salutationAnglais = "Hello, World!" //: Emoji characters are also defined in Unicode, so you can include emoji in strings.\ //: (On the Mac, type Command-Control-Space to bring up an emoji picker.) let welcomingPhrase = "Welcome! 😀" //: You can also use emoji in names. That can be fun in small doses, but many programmers find it difficult to type, difficult to read, and less expressive than using words for names. let 🍓🍏🍒🍐🍋🍇 = "Fruit Salad" //: Move on to the next page to see how to combine strings together.
Combining Strings
Programmers often need to combine strings together.
For example, you might see a message like Chris likes your post in a social media app.
In Swift, you can combine strings by adding them together:
// This might change over time let username = "Chris"
// This part of the message will get reused let likesYourPostMessage = "likes your post"
// Combine strings by using the plus sign let finishedMessage = username + " " + likesYourPostMessage //: You can see how the strings have been combined in the results sidebar. 👉 //: //: What happens if you don’t add the space between the two strings? //: - experiment: Declare `firstName` and `lastName` string constants for your first and last name.\ //:Combine them into a `fullName` constant.\ //:Combine your `firstName` and `likesYourPostMessage`\ //:Type each line of code below the relevant comment below. // Declare a firstName constant
// Declare a lastName constant
// Combine the strings into a fullName constant
// Combine your first name with likesYourPostMessage
//: Next, find out how building strings by adding them can get complicated.
Fill in the Blanks
Combining strings by adding them together works very well. You may have noticed, however, that you needed to remember to add spaces between the words. Otherwise the words all run together:
// Forgot to add the space between the first name and last name. let fullName = "Johnny" + "Appleseed" //: //: Imagine an app that welcomes the user when they arrive in a new city. You want the string to say something like:\ //: _Hello Tara, welcome to Paris!_\ //: You could build that string by adding strings together, but it gets a little complicated: //: let firstName = "Tara" let city = "Paris" let welcomeString = "Hello " + firstName + ", welcome to " + city + "!" //: //: For building more complex strings like this, it would be useful to have a way to define a fill-in-the-blanks string. Something like this: //: //: “Hello \_\_\_\_\_\_\_, welcome to \_\_\_\_\_\_\_!” //: //: Swift has a way to do this. The official name for this is _string interpolation_. This sounds complicated and difficult, but it’s basically just fill-in-the-blanks. //: //: Move on to see how to do this in Swift. //:
String Interpolation
In Swift, you can define a string with placeholders that will be replaced with values. It works a lot like the fill-in-the-blanks example from the previous page:
“Hello _______, welcome to _______!”
You don’t use blank spaces as placeholders in Swift. You use (name). The value of name replaces the placeholder.
Here it is in action. Notice in the results sidebar that the values of firstName and city are filled in:
let firstName = "Tim" let city = "Cupertino"
let welcomeString = "Hello \(firstName), welcome to \(city)" //: - experiment: Create your own string describing your favorite food.\ //: “I like \_\_\_\_\_ because it is \_\_\_\_\_.” //: // Change this to your favorite food let favoriteFood = "pie"
// Change this to why you like it let reason = "tasty"
// Define a string below in the pattern “I like ___ because it is ___.”
//: On the next page, see what happens with long strings.
Viewing Playground Results
What if you define a long string in a playground? You’ll notice that the longer string is cut off at the end in the results sidebar. 👉
let spelledOutNumber = "six" let meal = "breakfast" let aliceQuotation = "Why, sometimes I’ve believed as many as \(spelledOutNumber) impossible things before \(meal)!" //: In the results sidebar, move the cursor over the line that begins “Why, sometimes I’ve believed…”. When you do, that result will be highlighted and two controls will appear: //: //:  //: Click the control that looks like an eye. This is the QuickLook control. A popover will appear showing you more of the string value. //: //: Move the cursor over the control that looks like an outlined rectangle. This is the _show result_ button. If you click it, it will be highlighed and the result of that line of code will be added directly below the code. You can click this control again to hide the result. //: //: For now, leave the result of the long string showing. Change the values of the spelled out number and the meal. Notice how the result changes inline in the playground. //: //: On the next page, take these strings even further.
More than Strings
String interpolation is a powerful way to build strings. In addition to substituting string values, you can substitute in other values too, like numbers or even calculations.
let goalieName = "Alison" let firstHalfSaves = 3 let secondHalfSaves = 6 let overtimeSaves = 2 let goalieReportString = "At the game yesterday, \(goalieName) had \(firstHalfSaves) saves in the first half, \(secondHalfSaves) in the second half and \(overtimeSaves) saves in overtime, for a total of \(firstHalfSaves + secondHalfSaves + overtimeSaves) saves." //: /*: - experiment: People have been playing fun fill-in-the-blank games for a long time. You can create a basic version of this kind of game in the playground: - Make up a short fill-in-the-blank story, or use the one below. - Create a string or number constant for every blank. - Use string interpolation to fill in the blanks in the story.
Sample story: “Today was a big day for . They had finally saved up dollars and were going to buy a . They went to the feeling very . But then they felt . They were all out of !” */ // Add your version of the story below
//: //: //: Next you’ll see a few more tricks with strings.
The Great Escape
You’ve defined a lot of strings by putting characters between quotation marks. But what if you want a string that includes a quotation mark?
You could try just adding quotation marks in the middle of a string.
Uncomment the badString line of code below to see what happens:
You get an error because Swift thinks the string definition is finished at the second quotation mark, just before the Hi. Then it doesn’t know how to interpret the rest of the line of code.
When you’re done exploring, comment the code again, so the error goes away.
The Solution
To include a quotation mark in a string, type a backslash before the quotation mark:
let stringWithQuotationMarks = "He said, \"Hi there!\" as he passed by." //: The backslash tells Swift to treat what comes next as special. Since the quotation mark character follows the backslash, Swift treats it differently. It includes the quotation mark in the string, rather than ending the definition of the string. //: //:Because the backslash character is how you “escape” from the normal behavior of a string, it’s called an _escape character_. //: //: Now take a look at more things you can do with the escape character.
Escape Sequences
The pattern of an escape character followed by something that’s treated specially
E.g.,
// The backslash followed by a quotation mark is an escape sequence. let favoriteQuotation = "Hamlet said, \"To be, or not to be?\""
// Another escape sequence is the placeholder in an interpolated string. let flavor = "chocolate" let iceCreamAnnouncement = "The flavor of the day is \(flavor)" //: Some escape sequences in Swift let you insert invisible characters. One that you’ll use often is the _newline_ character. As you might guess from the name, this character makes the text skip to a new line. //: //: The escape sequence for a newline is the backslash character followed by the letter “n”: let startOfAPoem = "Roses are red.\nViolets are blue." //: In the result displayed above, notice a new line starts where the `\n` appears in the string. //: - note: If the result is not visible, click the show result button for the line of code above. //: //: Also notice that the string in the results sidebar shows the `\n` instead of skipping a line.\ //: That’s because the results sidebar can only use one line to show results. //: //: //: Move on to the next page to wrap things up. //:
Wrapup
In this section you’ve seen a lot of ways to deal with text information in Swift:
Why programmers refer to text data as strings.
How to declare string constants.
How to combine strings by adding them together.
How to build complicated fill-in-the-blank strings with string interpolation.
How to use escape sequences to add special characters in a string.
Practice what you’ve learned so far with some additional exercises.
Exercise: Making a List
Lists are great. Here are some constants describing some of the things you’ve learned about strings so far:
let constants = "Declaring string constants" let unicode = "Unicode characters (😎)" let combining = "Combining strings using +" let interpolation = "String interpolation (aka Fill in the Blanks)" let escaping = "Escape characters for \"special powers\"" let newline = "Making new lines" /*: - experiment: Make a new string constant that is a list of the things you’ve learned, with each entry on a new line. Make sure you add the result to the playground page so that you can see the list properly. */
Exercise: A Restaurant
let customerOrderOne = "fish" let customerOrderTwo = "risotto" let customerOrderThree = "soup"
let serverResponseToTableOne = “Let me make sure I’ve got this right: fish, risotto, and soup. Is that everything?”
let tableOneResponse = “Yes, thank you!”
/*: ### Later that day:
Three other guests enter and place their orders: */
let customerOrderFour = “돌솥비빔밥”
let customerOrderFive = “Pasztecik szczeciński”
let customerOrderSix = “小笼包”
/*: The server speaks all of these languages and confidently repeats the orders back to the group.
- callout(Exercise):
Make sure the server repeats the order correctly without copying and pasting or retyping any of the orders.
*/
let serverResponseToTableTwo = “Let me make sure I’ve got this right: “
let tableTwoResponse = “Perfect, merci bien.”
Exercise: Go! Fight! Win!
Many schools have “fight songs”: Students learn at least some portion of the words and then sing the songs together loudly at school events like sports games.
You’ve decided that your school’s fight song needs a rewrite. You want to edit the song in code so you don’t have to copy and paste as much while you work.
Edit the song to have more than a repeated refrain.
Edit the refrain to have actual words.
Edit the refrain to use the schoolName at least twice.
Test your work by changing the school name to a fictional school.
Use string interpolation in case you decide to sell your brilliant song to another school.
Use the show result button to view the results of your work.
let schoolName = "YOUR SCHOOL NAME" let refrain = "hmm hmm HMMM hm-hmm \(schoolName) hmm hmm HMMMMM"
let song = “(refrain)\n(refrain)\nYes, (refrain)”
Exercise: Displaying Values
You may recall from an earlier playground an exercise that involved calculating the space remaining on an iPhone. You had the following information:
The capacity of an iPhone is measured in gigabytes (GB). The iPhone in question has 8GB of storage.
A gigabyte is about 1,000 megabytes (MB)
The phone already has 3GB of stuff on it
One minute of video takes 150MB of space
Create a string that tells the user how many minutes of video they can store on the phone. You’ll first need to perform the calculation steps, then use string interpolation to display the answer - which should look like this:
You can record XXX more minutes of video.
Hint: Do all of your calculations in megabytes.