String Manipulation
Trim, split, join, replace, and index strings using Swift's Unicode API.
Code
import Foundation
let raw = " Hello, Swift World! "
// Trimming
let trimmed = raw.trimmingCharacters(in: .whitespaces)
print(trimmed)
// Splitting
let parts = "a,b,,c".split(separator: ",").map(String.init)
print(parts)
// Joining
let joined = ["x", "y", "z"].joined(separator: "-")
print(joined)
// Replacing
let replaced = "hello".replacingOccurrences(of: "l", with: "L")
print(replaced)
// Subscript with index
let s = "Swift"
let i = s.index(s.startIndex, offsetBy: 2)
print(s[i]) // i
let range = s.startIndex..<i
print(s[range]) // Sw
// Multi-line string
let multi = """
Line 1
Line 2
"""
print(multi)
// Formatting numbers
let pi = String(format: "%.2f", 3.14159)
print(pi)
// Date formatting
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
print(fmt.string(from: Date()))Explanation
Swift strings are Unicode-correct collections of grapheme clusters, so indexing uses String.Index rather than integers. Helpers like trimmingCharacters, split, joined, and replacingOccurrences cover the common string operations. String(format:) and DateFormatter bridge to the C-style format and locale-aware date formatting.
More Swift Snippets
Optionals
Use optional binding, nil-coalescing, chaining, and guard for safe unwrapping.
Closures
Define closure expressions, capture state, and pass escaping callbacks.
Protocols
Define contracts, conform with structs, and add default behavior via extensions.
Generics
Write type-parameterized functions and types with protocol constraints.
Structs and Classes
Compare value-type structs with reference-type classes and inheritance.
Error Handling
Throw and catch typed errors with do-catch, try?, try!, and rethrows.