Type conversion is always explicit in Swift - Time & Space Complexity
When we convert types in Swift, the computer must do extra work to change one type to another.
We want to see how this extra work grows when we convert many values.
Analyze the time complexity of the following code snippet.
let numbers = [1, 2, 3, 4, 5]
var doubles: [Double] = []
for number in numbers {
let converted = Double(number)
doubles.append(converted)
}
This code converts each integer in an array to a double and stores it in a new array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array and converting each integer to a double.
- How many times: Once for each item in the input array.
Each new number means one more conversion and one more append operation.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 conversions and 10 appends |
| 100 | 100 conversions and 100 appends |
| 1000 | 1000 conversions and 1000 appends |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to convert grows in a straight line as the list gets bigger.
[X] Wrong: "Type conversion happens automatically and instantly without extra work."
[OK] Correct: Each conversion requires the computer to do work, so it takes time proportional to how many items you convert.
Understanding how explicit type conversion affects performance helps you write clear and efficient code, a skill valued in many programming tasks.
What if we converted a nested array of integers to doubles? How would the time complexity change?
Practice
let x = 5 and let y = 3.2 are different types. What happens if you try to add x + y without conversion?Solution
Step 1: Understand Swift's type safety
Swift requires explicit type conversion to avoid unexpected behavior.Step 2: Check adding Int and Double without conversion
Trying to addIntandDoubledirectly causes a compile-time error.Final Answer:
It causes a compile-time error because Swift does not convert types automatically. -> Option BQuick Check:
Int + Double without conversion causes compile error [OK]
- Assuming Swift converts Int to Double automatically
- Thinking the result is always an Int
- Believing silent conversion happens
num = 10 to a Double in Swift?Solution
Step 1: Recall Swift's explicit conversion syntax
Swift uses the target type name as a function to convert values.Step 2: Identify correct syntax for Int to Double
The correct syntax isDouble(num). Other options are invalid in Swift.Final Answer:
let d = Double(num) -> Option CQuick Check:
Target type as function: Double(num) [OK]
- Using 'as' for numeric conversion
- Calling non-existent methods like toDouble()
- Using custom convert functions not in Swift
let a: Int = 7 let b: Double = 3.5 let c = Double(a) + b print(c)
Solution
Step 1: Convert Int to Double explicitly
ais Int 7, converted to Double 7.0 usingDouble(a).Step 2: Add converted Double and b
Adding 7.0 + 3.5 results in 10.5.Final Answer:
10.5 -> Option AQuick Check:
7.0 + 3.5 = 10.5 [OK]
- Forgetting to convert Int to Double
- Expecting integer addition result
- Assuming implicit conversion
let str = "123" let num = Int(str) let result = num + 10 print(result)
Solution
Step 1: Understand Int initializer returns optional
Int(str)returnsInt?because conversion might fail.Step 2: Adding optional Int and Int causes error
You cannot addInt?andIntdirectly without unwrapping.Final Answer:
Cannot add Int? and Int without unwrapping -> Option DQuick Check:
Int(str) returns Int?, must unwrap before adding [OK]
- Ignoring optional unwrapping
- Assuming Int(str) returns Int directly
- Trying to add optional and non-optional
let arr = ["1", "2", "three", "4"]. You want to convert them to Ints and sum only the valid numbers. Which Swift code correctly does this?Solution
Step 1: Use compactMap to convert and filter valid Ints
compactMapconverts strings to Ints and removes nil values safely.Step 2: Use reduce to sum the valid Ints
reduce(0, +)sums all Ints in the array.Final Answer:
let sum = arr.compactMap { Int($0) }.reduce(0, +) -> Option AQuick Check:
compactMap filters nils, then sum [OK]
- Using map which keeps optionals causing errors
- Force unwrapping without checking validity
- Adding optionals directly without unwrapping
Ready to prove it?
Pass the test and this pattern moves unknown
