Strings and Characters

5.1 String Basics

var greeting = "Hello"
greeting += ", World"
greeting.append("!")
let multiline = """
    Dear user,
      Welcome to Swift.
    Regards
    """                                   // indentation stripped up to the closing quotes
let raw = #"No \(interpolation) or \n escapes here"#
let rawInterp = #"Value: \#(42)"#       // interpolation inside raw strings
let empty = ""
print(empty.isEmpty, greeting.count)   // count = number of Characters (graphemes)

5.2 Characters and Unicode

let flag: Character = "🇮🇳"
let word = "café"
print(word.count)                       // 4 (grapheme clusters)
print(word.unicodeScalars.count)        // 4 or 5 depending on composition
print(word.utf8.count, word.utf16.count)
for ch in "Swift" { print(ch) }
let combined = "e\u{301}"              // "é" (e + combining acute accent)
print(combined == "é")                 // true: canonical equivalence

5.3 Indexing (Strings Aren't Integer-Indexed)

Substrings share storage with the original string. Convert them to String for long-term storage.

let s = "Hello, Swift"
let first = s[s.startIndex]                              // "H"
let fifth = s[s.index(s.startIndex, offsetBy: 4)]        // "o"
let lastChar = s.last                                    // Character?
if let comma = s.firstIndex(of: ",") {
    let prefix = s[..<comma]                             // Substring "Hello"
    let owned = String(prefix)                           // convert to String for storage
}

5.4 Common String Operations

let text = "  Swift is fast and safe  "
text.trimmingCharacters(in: .whitespaces)       // Foundation
text.uppercased(); text.lowercased(); text.capitalized   // capitalized needs Foundation
text.contains("fast"); text.hasPrefix("  Sw"); text.hasSuffix("  ")
text.replacingOccurrences(of: "fast", with: "quick")     // Foundation
text.split(separator: " ")                               // [Substring]
text.components(separatedBy: " ")                        // Foundation, [String]
["a", "b", "c"].joined(separator: ", ")
String(repeating: "ab", count: 3)
String(text.reversed())
text.filter { !$0.isWhitespace }
Int("42"); Double("3.14"); String(255, radix: 16)        // "ff"
"apple".compare("Apple", options: .caseInsensitive)      // Foundation
"Swift".lowercased() == "swift"
let formatted = String(format: "%.2f", 3.14159)          // Foundation
let value = 3.14159.formatted(.number.precision(.fractionLength(2)))   // modern formatting

5.5 String Interpolation

let price = 9.99, qty = 3
print("Total: \(price * Double(qty))")
print("Items: \(qty, privacy: .public)")   // custom interpolation (os.Logger style)
extension String.StringInterpolation {
    mutating func appendInterpolation(currency value: Double) {
        appendLiteral(value.formatted(.currency(code: "USD")))
    }
}
print("Price: \(currency: 9.99)")          // "Price: $9.99"