Swift Strings
A String in Swift is a sequence of characters. Swift strings are powerful, Unicode-correct, and packed with built-in tools for searching, modifying, and formatting text. You use strings constantly — for user names, messages, file paths, URLs, and more.
Creating Strings
let greeting = "Hello, Swift!"
let empty = ""
let alsoEmpty = String()
var multiline = """
Line one
Line two
Line three
"""
print(multiline)Triple-quoted strings (""") preserve line breaks and are perfect for paragraphs, JSON templates, or HTML snippets.
String Interpolation
Embed any value directly inside a string using \(). Swift converts the value to text automatically.
let name = "Alice"
let age = 30
let score = 98.5
print("Name: \(name), Age: \(age), Score: \(score)")
// Output: Name: Alice, Age: 30, Score: 98.5
print("Next year she will be \(age + 1).")
// Output: Next year she will be 31.String Properties
let word = "Swift"
print(word.count) // Output: 5
print(word.isEmpty) // Output: false
print(word.uppercased()) // Output: SWIFT
print(word.lowercased()) // Output: swiftDiagram: String as a Character Sequence
"Swift" | S w i f t ↑ ↑ startIndex endIndex (past the last character) word.first → "S" word.last → "t" word.count → 5
Checking String Content
hasPrefix and hasSuffix
let filename = "report_2024.pdf"
print(filename.hasPrefix("report")) // Output: true
print(filename.hasSuffix(".pdf")) // Output: true
print(filename.hasSuffix(".docx")) // Output: falsecontains
let sentence = "Swift is fast and safe."
print(sentence.contains("fast")) // Output: true
print(sentence.contains("slow")) // Output: falseModifying Strings
Concatenation
var message = "Hello"
message += ", World"
message.append("!")
print(message) // Output: Hello, World!Replacing Substrings
var text = "I love cats. Cats are great."
let updated = text.replacingOccurrences(of: "cats", with: "dogs",
options: .caseInsensitive)
print(updated) // Output: I love dogs. dogs are great.Trimming Whitespace
let padded = " hello "
let trimmed = padded.trimmingCharacters(in: .whitespaces)
print(trimmed) // Output: "hello"Splitting and Joining
Split a String Into Parts
let csv = "Alice,Bob,Carol,Dave"
let names = csv.split(separator: ",")
print(names)
// Output: ["Alice", "Bob", "Carol", "Dave"]
for name in names {
print(name)
}Join an Array Into a String
let words = ["Swift", "is", "awesome"]
let joined = words.joined(separator: " ")
print(joined) // Output: Swift is awesome
let csv2 = words.joined(separator: ",")
print(csv2) // Output: Swift,is,awesomeString Comparison
let a = "apple"
let b = "Apple"
print(a == b) // false (case-sensitive)
print(a.lowercased() == b.lowercased()) // true
print(a.caseInsensitiveCompare(b) == .orderedSame) // trueSubstrings
Swift extracts substrings using string indices. A Substring shares memory with the original string, making it very efficient.
let email = "alice@example.com"
if let atSign = email.firstIndex(of: "@") {
let username = email[..<atSign]
print(username) // Output: alice
let domain = email[email.index(after: atSign)...]
print(domain) // Output: example.com
}Convert Substring to String
let sub = email.prefix(5)
let str = String(sub)
print(str) // Output: aliceString Formatting Numbers
let price = 9.5
let formatted = String(format: "Price: $%.2f", price)
print(formatted) // Output: Price: $9.50
let big = 1_234_567
let readable = String(format: "%d items", big)
print(readable) // Output: 1234567 itemsConverting Between Strings and Other Types
// String to Int
let numStr = "42"
if let number = Int(numStr) {
print(number + 8) // Output: 50
}
// String to Double
if let pi = Double("3.14159") {
print(pi * 2) // Output: 6.28318
}
// Int to String
let count = 100
let label = "Score: \(count)"
print(label) // Output: Score: 100Iterating Over Characters
let word2 = "Swift"
for char in word2 {
print(char)
}
// Output: S w i f t (each on its own line)
let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
let vowelCount = word2.lowercased().filter { vowels.contains($0) }.count
print("Vowels in Swift: \(vowelCount)") // Output: 1Diagram: Common String Operations
Original: " Hello, Swift! "
|
trimmed → "Hello, Swift!"
|
uppercased → "HELLO, SWIFT!"
|
split(separator: ",") → ["Hello", " Swift!"]
|
replacingOccurrences("Swift", "World") → "Hello, World!"
Raw Strings
Prefix and suffix a string with # to treat backslashes and quotes as literal characters. Useful for regular expressions and file paths.
let path = #"C:\Users\Alice\Documents"#
print(path) // Output: C:\Users\Alice\Documents
let regex = #"\d{3}-\d{4}"#
print(regex) // Output: \d{3}-\d{4}Summary
Swift strings are Unicode-safe sequences with a rich set of methods. Use interpolation (\()) to embed values, split and joined to work with parts, and prefix/suffix/firstIndex to extract substrings. Convert between strings and numbers with Int(), Double(), and String(format:). Strings are immutable when declared with let and fully mutable with var.
