Type casting with as, as?, as! in Swift - Time & Space Complexity
When we use type casting in Swift, the program checks if a value can be treated as another type.
We want to know how the time it takes to do this changes as the data size grows.
Analyze the time complexity of the following code snippet.
class Animal {}
class Dog: Animal {}
let animals: [Animal] = [Dog(), Dog(), Dog(), Dog(), Dog()]
for animal in animals {
if let dog = animal as? Dog {
print("This is a dog")
}
}
This code tries to check each animal in a list to see if it is a Dog using safe type casting.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop goes through each element in the array.
- How many times: Once for every animal in the list.
Each animal is checked one by one, so the work grows as the list gets bigger.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 type checks |
| 100 | 100 type checks |
| 1000 | 1000 type checks |
Pattern observation: The number of checks grows directly with the number of animals.
Time Complexity: O(n)
This means the time to check all animals grows in a straight line as the list gets bigger.
[X] Wrong: "Type casting 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 work.
Understanding how type casting scales helps you write efficient code when working with collections of mixed types.
"What if we used a dictionary to group animals by type instead of checking each one? How would the time complexity change?"