Strings & String Interpolation

Reviewed & published by Brayan K

Text is everywhere in real apps. By the end of this lesson you'll create strings, splice values into them with interpolation \(...), write multiline literals with """, and reach for the most common String methods with confidence.

Part of the free Swift course at LearnCodingFast — hands-on lessons with worked examples and the output they print, plus practice exercises and a quick quiz.

What You'll Learn in This Lesson

1️⃣ Creating & Joining Strings

A String is text in double quotes. Join strings with +, grow a var with +=, and inspect length with count or emptiness with isEmpty.

// A String is text, always written in "double quotes".
let greeting = "Hello, Swift!"
print(greeting)

// Join strings with + ...
let first = "Ada"
let last  = "Lovelace"
let full  = first + " " + last
print(full)                     // Ada Lovelace

// ... or build them up with +=
var sentence = "Learning"
sentence += " Swift"
sentence += " is fun"
print(sentence)                 // Learning Swift is fun

// Length and emptiness
print(full.count)               // 12  (number of characters)
print("".isEmpty)               // true
print(full.isEmpty)             // false

2️⃣ String Interpolation

Interpolation drops a value straight into text with \(...) — a backslash, then your expression in parentheses. You can run a real calculation inside the parentheses, not just name a variable.

// String interpolation drops a value straight into text with \(...).
let name = "Sam"
let unread = 5
print("Hi \(name), you have \(unread) new messages.")

// You can run real expressions inside the parentheses:
let price = 4.0
let qty = 3
print("\(qty) coffees cost £\(price * Double(qty))")   // 3 coffees cost £12.0

// It reads far better than gluing pieces together with +.
let city = "Paris"
let temp = 21
print("It is \(temp)°C in \(city) today.")

3️⃣ Multiline Strings

Wrap text in triple quotes """ (on their own lines) to span multiple lines without escapes. Interpolation works inside them too — perfect for templates and messages.

// A MULTILINE string uses triple quotes """ on their own lines.
let poem = """
Roses are red,
Violets are blue,
Swift makes strings
A pleasure to use.
"""
print(poem)

// Interpolation works inside multiline strings too.
let user = "Ada"
let welcome = """
Dear \(user),
Welcome aboard!
"""
print(welcome)

4️⃣ Common Methods & Characters

Swift's String API is rich. Methods like uppercased(), contains, and hasPrefix return new values without changing the original. Looping over a string yields each Character — Swift's single-character type.

// Common String methods — each returns a NEW string (originals are unchanged).
let title = "  Swift Strings  "

print(title.uppercased())                 //   SWIFT STRINGS
print(title.lowercased())                 //   swift strings
print(title.trimmingCharacters(in: .whitespaces))   // "Swift Strings"

let phrase = "the quick brown fox"
print(phrase.contains("quick"))           // true
print(phrase.hasPrefix("the"))            // true
print(phrase.hasSuffix("dog"))            // false
print(phrase.replacingOccurrences(of: "quick", with: "slow"))

// Iterate over each Character (Swift's single-character type).
for ch in "Hi!" {
    print(ch)                             // H, then i, then !
}

Your turn. Fill in the blanks, then run it and check the output.

// 🎯 YOUR TURN — replace each ___ then run it in SwiftFiddle.

let product = "Notebook"
let stock = 7

// 1) Print one line using interpolation, e.g. "We have 7 Notebook(s)."
print("We have ___(stock) ___(product)(s).")   // 👉 replace ___ with the backslash \

// 2) Print the product name in UPPERCASE.
print(product.___())                            // 👉 replace ___ with uppercased

// 3) Print how many characters are in the product name.
print(product.___)                              // 👉 replace ___ with count

// ✅ Expected output:
//    We have 7 Notebook(s).
//    NOTEBOOK
//    8

Pro Tips

Common Errors (and the fix)

📋 Quick Reference

TaskCodeResult
Interpolate"Hi \(name)"Hi Sam
Lengths.countnumber of chars
Empty?s.isEmptytrue / false
Uppercases.uppercased()new string
Containss.contains("x")true / false
Multiline"""...lines..."""spans lines

Mini-Challenge: Greeting Card

Build it, run it, and check your output against the example in the comments.

// 🎯 MINI-CHALLENGE: Greeting card
// 1. Make a 'let name' (a String) and a 'let age' (an Int).
// 2. Build a MULTILINE string (triple quotes) that reads:
//        Hello NAME!
//        You are AGE years old.
//    using \(name) and \(age) interpolation.
// 3. Print it, then print name.count to show how long the name is.
//
// ✅ Example output (name="Mia", age=30):
//    Hello Mia!
//    You are 30 years old.
//    3

// your code here

🎉 Lesson Complete!

Practice quiz

How do you write a string literal in Swift?

  • With 'single quotes'
  • With backticks
  • With "double quotes"
  • With /slashes/

Answer: With "double quotes". Swift string literals always use double quotes.

What is the correct string interpolation syntax?

  • \(name)
  • ${name}
  • #{name}
  • {name}

Answer: \(name). Swift interpolates with a backslash and parentheses: \(name).

Which delimiter begins and ends a multiline string literal?

  • Single "
  • Triple '''
  • <<<
  • Triple """

Answer: Triple """. Multiline strings are wrapped in triple double-quotes """.

What does "abc".count return?

  • 2
  • 3
  • 4
  • nil

Answer: 3. count returns the number of characters; "abc" has 3.

What is the type of a single character extracted from a String?

  • Character
  • String
  • Char
  • UInt8

Answer: Character. Swift's single-character type is Character.

How do you check whether a String is empty?

  • s.empty
  • s.count == nil
  • s.isEmpty
  • s == null

Answer: s.isEmpty. The isEmpty property is true when the string has no characters.

What does "Hello".uppercased() return?

  • "hello"
  • "HELLO"
  • "Hello"
  • It mutates in place and returns nothing

Answer: "HELLO". uppercased() returns a new uppercase string.

Can you concatenate two strings with the + operator?

  • No, you must use append only
  • Only with numbers
  • Only inside interpolation
  • Yes, "a" + "b" gives "ab"

Answer: Yes, "a" + "b" gives "ab". The + operator joins two strings into a new string.

Which method tells you if a string contains a substring?

  • s.has("x")
  • s.contains("x")
  • s.includes("x")
  • s.find("x")

Answer: s.contains("x"). contains(_:) returns a Bool indicating presence of the substring.

Are Swift Strings value types (copied on assignment)?

  • No, they are reference types
  • Only multiline strings
  • Yes, String is a value type
  • Only empty strings

Answer: Yes, String is a value type. String is a value type, so assigning it makes an independent copy.

Continue this course

Frequently asked questions

How does string interpolation work in Swift?

You write a backslash followed by parentheses around any expression: "Hi \(name)". Swift evaluates whatever is inside the parentheses — a variable, a calculation, a function call — converts the result to text, and splices it into the string. It is far more readable than concatenating pieces with +.

What is a multiline string and when should I use one?

A multiline string is wrapped in triple double-quotes (""") on their own lines, letting you write text that spans several lines without escape characters. It is ideal for blocks of text like JSON, SQL, templates, or formatted messages. The indentation of the closing delimiter sets the baseline that Swift strips from each line.

What is the difference between String and Character?

String is a sequence of characters (the whole piece of text), while Character is a single human-readable character — which may be made of several Unicode scalars, such as an emoji with a skin-tone modifier. When you loop over a String with a for-in loop, each element you get is a Character.

Why doesn't a String have integer indexes like text[0]?

Because a Swift Character can span multiple bytes (think emoji or accented letters), a fixed integer offset wouldn't reliably land on a character boundary. Swift uses String.Index instead. For simple needs, use methods like first, last, count, or convert to an Array(string) when you really need positional access.

Are Swift strings mutable, and are they value types?

A String declared with var is mutable — you can append to it or change it. String is a value type, so assigning one string to another (or passing it to a function) makes an independent copy; changing one never affects the other.