Swift: Swift Strings and Characters
Strings are the most frequently used data type in everyday development. This lesson gives you a complete tour of String and Character operations in Swift.
1. What You'll Learn
- Creating, concatenating, and comparing Strings
- String interpolation syntax and formatted output
- Multiline string indentation rules
- The Character type and iterating over strings
- Common string methods: count, hasPrefix, uppercased, and more
2. A True Story: A Customer Operations Specialist
(1) The Pain Point: Manual Email Template Concatenation Was Slow and Error-Prone
Charlie is a customer operations specialist at a SaaS company, sending personalized emails to over 2,000 customers every week. He started by using plus signs to concatenate strings:
let firstName = "Alice"
let lastName = "Johnson"
let product = "Premium Plan"
let price = "299.00"
let email = "Dear " + firstName + " " + lastName + ",\n\nThank you for purchasing " + product + "!\nYour payment: $" + price + ".\n\nBest regards,\nCharlie"
The code was long and hard to maintain. Any template format change meant rewriting the entire thing. Last week he accidentally sent "Dear AliceJohnson" (missing a space) to over 300 customers.
(2) The Solution: String Interpolation
Charlie switched to Swift's string interpolation syntax, and the template became clean and readable:
let firstName = "Alice"
let lastName = "Johnson"
let product = "Premium Plan"
let price = "299.00"
let email = """
Dear \(firstName) \(lastName),
Thank you for purchasing \(product)!
Your payment: $\(price).
Best regards,
Charlie
"""
print(email)
Output:
TEXT 📖 Display onlyDear Alice Johnson, Thank you for purchasing Premium Plan! Your payment: $299.00. Best regards, Charlie
(3) The Result: Template Code Maintainability Improved
| Dimension | Before (Concatenation) | After (Interpolation) |
|---|---|---|
| Code per email | 8 lines of concatenation + escaping | 4 lines of interpolation |
| Template edit time | 5-10 minutes | 30 seconds |
| Error rate | 3-5 per month | 0 |
| Readability | Mixed symbols, extremely hard to proofread | Nearly plain text |
3. Creating and Concatenating Strings
Swift's String type is powerful and offers multiple ways to create and manipulate strings.
(1) String Literals
Create strings by wrapping text in double quotes. Swift supports Unicode, including emoji:
let greeting = "Hello, Swift!"
let empty = "" // Empty string
let emoji = "🚀" // Unicode support
| Creation Method | Syntax | Description |
|---|---|---|
| Literal | let s = "Hello" |
Most common |
| Empty string | let s = "" |
Empty string |
| Initializer | String() |
Creates an empty string |
| Repeating | String(repeating: "!", count: 3) |
"!!!" |
graph LR
A[String Creation] --> B["Literal: \"Hello\""]
A --> C["Initializer: String()"]
A --> D["Repeating: repeating count"]
A --> E["Concatenation: +"]
A --> F["Interpolation: \\(value)"]
(2) String Concatenation
Use + or += to concatenate strings, or the append method:
let firstName = "Alice"
let lastName = "Johnson"
// Using + for concatenation
let fullName = firstName + " " + lastName
print(fullName) // Alice Johnson
// Using += to append
var message = "Hello"
message += ", "
message += firstName
print(message) // Hello, Alice
// Using the append method
var greeting2 = "Welcome"
greeting2.append("!")
print(greeting2) // Welcome!
▶ Example: Email Address Generator
// ============================================
// Generate email addresses from user info
// Demonstrates string creation and concatenation
// ============================================
let domain = "@example.com"
let alice = "alice.johnson"
let bob = "bob.smith"
let charlie = "charlie.brown"
let email1 = alice + domain
let email2 = bob + domain
let email3 = charlie + domain
print(email1)
print(email2)
print(email3)
// Build a full URL
let scheme = "https://"
let site = "api."
let fullURL = scheme + site + domain
print("API URL: \(fullURL)")
Output:
TEXT 📖 Display onlyalice.johnson@example.com bob.smith@example.com charlie.brown@example.com API URL: https://api.example.com
4. String Interpolation and Common Methods
String interpolation is one of Swift's most powerful string features, allowing you to embed variables, expressions, and even function calls directly in strings.
(1) String Interpolation
Use the \(expression) syntax to embed any value into a string:
let name = "Alice"
let age = 28
let height = 1.75
let intro = "My name is \(name), I am \(age) years old and \(height) meters tall."
print(intro)
// My name is Alice, I am 28 years old and 1.75 meters tall.
// Expressions inside interpolation
let price = 29.99
let qty = 3
let summary = "Total: $\(price * Double(qty))"
print(summary)
// Total: $89.97
| Interpolation Content | Syntax | Result |
|---|---|---|
| Variable | \(name) |
The variable's value |
| Expression | \(price * 0.9) |
Calculated result |
| Method call | \(name.uppercased()) |
Method's return value |
| Multiple values | \(a) + \(b) = \(a + b) |
Embedded one by one |
(2) Common String Methods
Swift's String provides a rich set of built-in methods:
let text = "Hello, Swift!"
text.count // 13 (character count)
text.isEmpty // false
text.hasPrefix("Hello") // true
text.hasSuffix("Swift!") // true
text.uppercased() // "HELLO, SWIFT!"
text.lowercased() // "hello, swift!"
text.contains("Swift") // true
| Method | What It Does | Example | Result |
|---|---|---|---|
count |
Number of characters | "Hello".count |
5 |
isEmpty |
Whether it's empty | "".isEmpty |
true |
hasPrefix |
Whether it starts with a prefix | "Swift".hasPrefix("Sw") |
true |
hasSuffix |
Whether it ends with a suffix | "Swift".hasSuffix("ft") |
true |
uppercased |
Convert to uppercase | "Swift".uppercased() |
"SWIFT" |
lowercased |
Convert to lowercase | "Swift".lowercased() |
"swift" |
contains |
Whether it contains a substring | "Hello".contains("ell") |
true |
▶ Example: User Info Card
// ============================================
// Generate a formatted user info card
// Demonstrates string interpolation and common methods
// ============================================
let firstName = "Alice"
let lastName = "Johnson"
let email = "alice.johnson@example.com"
let role = "Admin"
// Use interpolation to combine info
let displayName = "\(firstName) \(lastName)"
let emailDomain = email.contains("@") ? email.split(separator: "@")[1] : "unknown"
// Validate format
let isValidEmail = email.contains(".") && email.contains("@")
let isAdmin = role.uppercased() == "ADMIN"
print("=== User Card ===")
print("Name: \(displayName)")
print("Email: \(email)")
print("Domain: \(emailDomain)")
print("Valid Email: \(isValidEmail)")
print("Admin: \(isAdmin)")
print("Name Length: \(displayName.count) chars")
Output:
TEXT 📖 Display only=== User Card === Name: Alice Johnson Email: alice.johnson@example.com Domain: example.com Valid Email: true Admin: true Name Length: 13 chars
5. Multiline Strings and Character
Swift provides triple-quote syntax for multiline strings, and the Character type represents a single character.
(1) Multiline Strings
Use three double quotes """ to wrap content, preserving line breaks and indentation:
let poem = """
Roses are red,
Violets are blue,
Swift is awesome,
And so are you!
"""
print(poem)
Output:
TEXT 📖 Display onlyRoses are red, Violets are blue, Swift is awesome, And so are you!
Indentation rules for multiline strings: the position of the closing """ determines how much leading whitespace is stripped from each line:
let indented = """
Line 1
Line 2
"""
// The 4 leading spaces on each line are stripped
| Feature | Single-line String | Multiline String |
|---|---|---|
| Syntax | "..." |
"""...""" |
| Line breaks | Must write \n |
Direct line breaks |
| Quotes | Must escape \" |
Can write " directly |
| Indentation | None | Based on closing delimiter |
(2) The Character Type
A Character represents a single visible character (Unicode scalar). A string is composed of multiple Characters:
let ch: Character = "A"
let emoji: Character = "🌟"
// Iterate over each character in a string
let greeting = "Hi!"
for char in greeting {
print(char)
}
// Output: H i !
▶ Example: Text Formatting
// ============================================
// Generate a formatted product description
// Demonstrates multiline strings and Character iteration
// ============================================
let productName = "Swift Pro"
let version = "2.0"
let features = ["Fast", "Safe", "Modern", "Open Source"]
// Use a multiline string to build the product description
let description = """
Product: \(productName)
Version: \(version)
Features:
- \(features[0])
- \(features[1])
- \(features[2])
- \(features[3])
"""
print(description)
// Iterate over each character in the product name
print("Product name characters:")
for ch in productName {
print("[\(ch)]", terminator: " ")
}
print()
Output:
TEXT 📖 Display onlyProduct: Swift Pro Version: 2.0 Features: - Fast - Safe - Modern - Open Source Product name characters: [S] [w] [i] [f] [t] [ ] [P] [r] [o]
6. Full Example: Customer Email Generator
// ============================================
// Customer email generator
// Demonstrates concatenation, interpolation, multiline, and methods
// ============================================
import Foundation
// 1. Customer data
let customerName = "Charlie Brown"
let projectName = "DataSync Pro"
let dueDate = "2026-08-15"
let amount = 2499.00
// 2. Email subject
let subject = "Invoice for \(projectName) - Due \(dueDate)"
print("Subject: \(subject)")
print(String(repeating: "=", count: subject.count + 10))
// 3. Email body (multiline string + interpolation)
let body = """
Dear \(customerName),
Thank you for choosing \(projectName).
Invoice Summary:
- Project: \(projectName)
- Amount: $\(String(format: "%.2f", amount))
- Due Date: \(dueDate)
Please make the payment by \(dueDate).
If you have any questions, feel free to reply.
Best regards,
Swift Tech Team
"""
print(body)
// 4. Email validation
let isValidSubject = subject.hasPrefix("Invoice")
let containsProjectName = body.contains(projectName)
let isFormatted = body.hasSuffix("Team\n")
print("=== Validation ===")
print("Valid Subject: \(isValidSubject)")
print("Contains Project: \(containsProjectName)")
print("Proper Formatting: \(isFormatted)")
print("Body Length: \(body.count) chars")
Output:
TEXT 📖 Display onlySubject: Invoice for DataSync Pro - Due 2026-08-15 ============================================== Dear Charlie Brown, Thank you for choosing DataSync Pro. Invoice Summary: - Project: DataSync Pro - Amount: $2499.00 - Due Date: 2026-08-15 Please make the payment by 2026-08-15. If you have any questions, feel free to reply. Best regards, Swift Tech Team === Validation === Valid Subject: true Contains Project: true Proper Formatting: true Body Length: 278 chars
❓ FAQ
""" serves as the baseline. The number of whitespace characters before the closing delimiter is stripped from the beginning of each content line. If a line has less indentation than the delimiter, no indentation is stripped from that line.📖 Summary
- Strings are created with double quotes; empty strings use
""orString() - Use
+to concatenate strings and+=to append content - String interpolation
\(expression)embeds any value into a string - Common methods: count, isEmpty, hasPrefix, hasSuffix, uppercased, contains
- Multiline strings use
"""; indentation is determined by the closing delimiter position - Character represents a single character; iterate over a String to get each Character
📝 Exercises
- Beginner: Use string interpolation to generate the sentence: "My name is X, I am Y years old." Store the name and age in variables.
- Intermediate: Write a program to validate a user-entered email address. Requirements: contains
@and., length greater than 5, output in lowercase. - Challenge: Use a multiline string to generate an HTML email template with a header, body, and footer, embedding the user name, product name, and price via interpolation.