Swift Strings
Swift's String type combines full Unicode support with a rich set of built-in methods, and string interpolation makes building formatted text almost effortless.
Creating and Interpolating Strings
A String is a sequence of characters wrapped in double quotes. Rather than concatenating pieces with +, Swift encourages string interpolation: writing \(expression) directly inside a string literal to embed any value, including the result of a computation.
String interpolation
let firstName = "Grace"
let lastName = "Hopper"
let fullName = "\(firstName) \(lastName)"
print(fullName) // Grace Hopper
let a = 6
let b = 7
print("\(a) times \(b) is \(a * b)") // 6 times 7 is 42Common String Methods and Properties
String comes with a large standard library of methods for measuring, transforming, and inspecting text. count gives the number of characters, isEmpty checks for an empty string, uppercased() and lowercased() change case, and hasPrefix / hasSuffix check the edges of a string.
Everyday string methods
let message = " Hello, Swift! "
print(message.count) // 17, includes the spaces
print(message.trimmingCharacters(in: .whitespaces)) // "Hello, Swift!"
print(message.uppercased()) // " HELLO, SWIFT! "
print(message.contains("Swift")) // true
print("Hello".hasPrefix("He")) // true
print("Hello".hasSuffix("lo")) // trueCombining and Splitting Strings
Strings can be joined with + or the append() method, and split apart with components(separatedBy:) or the newer split(separator:) method, which returns an array of substrings. These operations are essential when parsing user input or formatted text like CSV rows.
Joining and splitting
var greeting = "Hello"
greeting += ", " + "World!"
print(greeting) // "Hello, World!"
let csvLine = "apple,banana,cherry"
let fruits = csvLine.components(separatedBy: ",")
print(fruits) // ["apple", "banana", "cherry"]
print(fruits.count) // 3- String interpolation \( ) embeds any expression directly inside a string literal.
- count, isEmpty — measure and check strings without extra imports.
- uppercased(), lowercased(), trimmingCharacters(in:) — common transformations.
- hasPrefix(_:), hasSuffix(_:), contains(_:) — substring checks.
- components(separatedBy:) — splits a string into an array of substrings.
Quick Reference: String Methods
Exercise: Swift Strings
How do you write a multi-line string literal in Swift?