Strings and Characters in Swift: Unicode, Indexing, Substrings, Searching, Splitting and Formatting Text
Strings Are Collections of Characters
swift
let word = "Swift"
for ch in word { print(ch, terminator: ".") }
print("")
print(word.count, word.first as Any, word.last as Any)
print(word.reversed().map(String.init).joined())
Output
S.w.i.f.t. | 5 Optional("S") Optional("t") | tfiwS
Why Indexing Is Special
A character can be made of several Unicode pieces, so Swift cannot jump to the 3rd character with a simple number. You use String.Index values.
swift
let s = "Hello"
let i = s.index(s.startIndex, offsetBy: 1)
print(s[i])
let end = s.index(s.endIndex, offsetBy: -1)
print(s[i...end])
let flag = "e\u{301}" // e + combining accent
print(flag, flag.count, flag.unicodeScalars.count)
Output
e | ello | eĢ 1 2
Substrings
Slicing a string gives a Substring, which shares memory with the original. Convert with String(...) before keeping it for long.
swift
let sentence = "swift is fun"
let parts = sentence.split(separator: " ")
print(parts, parts.count)
let title = parts.map { $0.prefix(1).uppercased() + $0.dropFirst() }.joined(separator: " ")
print(title)
Output
["swift", "is", "fun"] 3 | Swift Is Fun
Searching and Changing
swift
import Foundation
let text = " a,b,c "
print(text.trimmingCharacters(in: .whitespaces))
print("one-two-three".replacingOccurrences(of: "-", with: "+"))
print("Swift".hasSuffix("ft"), "Swift".contains("if"))
print("x".padding(toLength: 4, withPad: "-", startingAt: 0))
Output
a,b,c | one+two+three | true true | x---
Formatting Numbers
swift
import Foundation
let pi = 3.14159265
print(String(format: "%.2f", pi))
print(pi.formatted(.number.precision(.fractionLength(3))))
Foundation Some string helpers such as trimming and replacing come from the Foundation framework. Add import Foundation to use them.
Common Mistakes
- Using integer offsets on a String like an array
- Keeping a long-lived Substring that holds a large string in memory
- Forgetting
import Foundation for trimming and replacing helpers
Practice
- Write a function that checks if a string is a palindrome
- Count vowels in a sentence
- Capitalize every word in a title
Conclusion
Swift strings are Unicode-correct. Use indexes, split and Foundation helpers for everyday text work.
Quick Summary: Characters; String.Index; substrings; search; format.