Character and String types in Swift - Time & Space Complexity
When working with characters and strings in Swift, it's important to know how the time to process them changes as the string gets longer.
We want to understand how operations like counting characters or accessing parts of a string grow with the string size.
Analyze the time complexity of the following code snippet.
let greeting = "Hello, Swift!"
var count = 0
for char in greeting {
count += 1
}
print("Total characters: \(count)")
This code counts how many characters are in the string by looping through each character one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character in the string.
- How many times: Once for every character in the string.
As the string gets longer, the loop runs more times, once per character.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 loops |
| 100 | 100 loops |
| 1000 | 1000 loops |
Pattern observation: The number of operations grows directly with the number of characters.
Time Complexity: O(n)
This means the time to count characters grows in a straight line with the string length.
[X] Wrong: "Accessing any character in a Swift string is instant, so looping is always fast."
[OK] Correct: Swift strings use complex encoding, so accessing characters by position can take time. Looping through each character is needed and takes time proportional to string length.
Understanding how string operations scale helps you write efficient code and explain your reasoning clearly in interviews.
"What if we changed the loop to access characters by index instead of using a for-in loop? How would the time complexity change?"