Swift: Strings – code examples
Manipulating text
Strings#string#split#trim#foundation
Use case: Cleaning, splitting, and checking user input (search, forms, log lines).
import Foundation
let s = " Swift is fun "
let sauber = s.trimmingCharacters(in: .whitespaces)
print(sauber.uppercased(), sauber.count) // SWIFT IS FUN 12
print(sauber.split(separator: " ").map(String.init))
print(sauber.hasPrefix("Swift"), sauber.contains("is"))
print(sauber.replacingOccurrences(of: "fun", with: "great"))
print(String(sauber.reversed()))count counts characters (graphemes), not bytes. trimmingCharacters and replacingOccurrences come from Foundation.
Counting words
Strings#dictionary#count#sort
Use case: Text analysis, e.g. the most frequent words in a document.
let text = "this is a test this is good"
var zaehler: [String: Int] = [:]
for wort in text.split(separator: " ") {
zaehler[String(wort), default: 0] += 1
}
let top = zaehler.sorted { ($0.value, $1.key) > ($1.value, $0.key) }.prefix(2)
print(top.map { "\($0.key): \($0.value)" }) // ["is: 2", "this: 2"]default: 0 saves you the check for missing keys. When sorting, the second tuple value ensures a fixed order on ties.
Regular expression
Strings#regex#pattern#string
Use case: Finding email addresses, phone numbers, or patterns in text.
let text = "Contact: ada@example.com, bob@test.org"
let muster = /[\w.]+@[\w.]+\.\w+/
let mails = text.matches(of: muster).map { String($0.output) }
print(mails) // ["ada@example.com", "bob@test.org"]
print("Phone 12345".replacing(/\d+/, with: "#")) // Phone #Swift Regex (since Swift 5.7, macOS 13) checks patterns at compile time. matches(of:) returns all matches. Slash literals are the default from Swift 6 mode onward; before that you need the feature BareSlashRegexLiterals or try Regex("...").