Strings
Swift strings are Unicode-correct: they iterate by extended grapheme clusters, not bytes or code units. The price is no O(1) indexing — positions use String.Index.
The strings API you actually use
EXAMPLE
let name = "Ada Lovelace"
print(name.count) // 12 (visible characters)
print(name.uppercased())
print(name.split(separator: " ")) // ["Ada", "Lovelace"]
// Interpolation
let age = 36
let greeting = "Hi, \(name)! You are \(age)."
// Multi-line literal
let body = """
Dear \(name),
Welcome to Swift.
--
Team
"""
// Mutating
var s = "Hello"
s.append(", world")
s += "!"
// Indices — NOT Int. Use String.Index.
let first = name[name.startIndex] // 'A'
let four = name.index(name.startIndex, offsetBy: 4)
let rest = name[four...] // "ovelace"
// Find / replace
if let r = name.range(of: "Lovelace") {
print(name[r])
}
let patched = name.replacingOccurrences(of: "Lovelace", with: "the Countess of Lovelace")
// Iterate as Characters / Unicode / UTF-8
for ch in name { print(ch) } // grapheme clusters
name.unicodeScalars.forEach { print(\$0.value) }
name.utf8.forEach { print(\$0) }
Why it matters
String length isn’t bytes. \"\u{1F1E6}\u{1F1FA}\" (🇦🇺) has count == 1 but utf8.count == 8. Pick the view that matches your need.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
let name = "Ada" let greet = "Hello, \(name)!" print(greet.uppercased()) print(name.count)Try it Yourself »
Discussion
Loading…