Strings, characters and interpolation
Strings, characters and interpolation
A report should display a name and score together without manually building every message. Swift string interpolation inserts a value inside text using a backslash followed by parentheses. String also understands Unicode text, so visible characters do not always correspond to one byte.
What you’ll learn
- Build a report sentence with interpolation.
- Distinguish Unicode character count from encoded byte length.
Strings, characters and interpolation in the example
Values
A report should display a name and score together without manually building every message.
ValuesInterpolation
A Character represents an extended grapheme cluster, which can contain multiple Unicode scalars.
InterpolationReadable sentence
Interpolation formats the two values into the message.
Readable sentence
How strings, characters and interpolation works
A Character represents an extended grapheme cluster, which can contain multiple Unicode scalars. String indexes therefore differ from ordinary integer array indexes. Use startIndex and index(after:) when navigating text rather than assuming every offset is one byte. String.count counts characters.
Work through strings, characters and interpolation
Save this complete program as main.swift and run it with the Swift toolchain. No separate input file is needed.
Swift · complete program
let name = "Diya"
let score = 80
let message = "\(name) scored \(score)"
print(message)
print("👩🏫".count)Expected output
Diya scored 80
1Follow the execution
Interpolation formats the two values into the message. The teacher emoji has a character count of one even though its Unicode representation combines multiple pieces. This example distinguishes a visible character from the size of its encoded bytes.
Try this program in the Swift compiler. Paste the complete source above.
Practice: Strings, characters and interpolation
Your task: How would you display the same sentence for Saira?
Swift · complete program
let name = "Diya"
let score = 80
let message = "\(name) scored \(score)"
print(message)
print("👩🏫".count)Worked answer
Change name to "Saira". The interpolation reads the new value, so the sentence updates without altering its structure or concatenating unrelated fragments.
Separate characters from bytes
Counting characters is not a guarantee about screen width or byte length. For files and network data, specify an encoding such as UTF-8 and operate on encoded data where appropriate. Prefer text APIs over manually slicing bytes as if they were characters.
Check your decision
Separate characters from bytes
Change name to "Saira". The interpolation reads the new value, so the sentence updates without altering its structure or concatenating unrelated fragments. Counting characters is not a guarantee about screen width or byte length.
Further reading: official Swift language guide.
Reaching the recap and completing the quizzes are separate milestones.