Is operator for type checking in Swift - Time & Space Complexity
We want to understand how the time it takes to check types grows as we check more items.
How does using the is operator affect performance when checking many objects?
Analyze the time complexity of the following code snippet.
let items: [Any] = [1, "hello", 3.14, true, 5]
var count = 0
for item in items {
if item is Int {
count += 1
}
}
print(count)
This code counts how many items in the list are integers using the is operator.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item and checking its type with
is. - How many times: Once for every item in the list.
As the list gets bigger, the number of type checks grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 type checks |
| 100 | 100 type checks |
| 1000 | 1000 type checks |
Pattern observation: The work grows directly with the number of items; double the items, double the checks.
Time Complexity: O(n)
This means the time to check types grows in a straight line with the number of items.
[X] Wrong: "Using the is operator is instant and does not depend on the number of items."
[OK] Correct: Each item must be checked one by one, so more items mean more checks and more time.
Knowing how type checks scale helps you write efficient code when working with mixed data types or collections.
"What if we used a nested loop to check types inside nested arrays? How would the time complexity change?"