0
0
Swiftprogramming~5 mins

String interpolation in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is string interpolation in Swift?
String interpolation is a way to insert values or expressions directly into a string by placing them inside \( ) within the string.
Click to reveal answer
beginner
How do you insert a variable named name into a string using string interpolation?
Use \(name) inside the string. For example: "Hello, \(name)!" will insert the value of name.
Click to reveal answer
intermediate
Can you use expressions inside string interpolation? Give an example.
Yes! You can put any expression inside \( ). For example: "2 + 3 = \(2 + 3)" will show 2 + 3 = 5.
Click to reveal answer
intermediate
What happens if you try to use string interpolation outside of a string literal?
String interpolation only works inside string literals. Using \( ) outside strings will cause a syntax error.
Click to reveal answer
beginner
Why is string interpolation useful compared to string concatenation?
String interpolation is easier to read and write. It avoids many + signs and automatically converts values to strings.
Click to reveal answer
How do you insert the value of a variable age into a string using Swift string interpolation?
A"I am + age + years old"
B"I am \(age) years old"
C"I am ${age} years old"
D"I am age years old"
Which of these is a valid string interpolation expression in Swift?
A"Sum is \(5 + 10)"
B"Sum is ${5 + 10}"
C"Sum is \{5 + 10}"
D"Sum is (5 + 10)"
What will this Swift code print? <br> let name = "Anna"<br>print("Hello, \(name)!")
AHello, \(name)!
BError
CHello, name!
DHello, Anna!
Can you use string interpolation to call a function inside a string in Swift?
AOnly if the function returns a string
BNo, functions cannot be used inside strings
CYes, by placing the function call inside \( )
DOnly if the function is declared inside the string
What is the output of this code? <br> print("3 * 4 = \(3 * 4)")
A3 * 4 = 12
B3 * 4 = \(3 * 4)
C3 * 4 = 3 * 4
DError
Explain how string interpolation works in Swift and why it is useful.
Think about how you put values inside strings easily.
You got /4 concepts.
    Write a Swift string that uses interpolation to show the result of 10 divided by 2.
    Use \( ) inside quotes with the division expression.
    You got /3 concepts.