Limitations and best practices in Swift - Time & Space Complexity
When we write code, it is important to know how fast it runs as the input grows.
This helps us avoid slow programs and choose better ways to solve problems.
Analyze the time complexity of this example function.
func findFirstEven(numbers: [Int]) -> Int? {
for number in numbers {
if number % 2 == 0 {
return number
}
}
return nil
}
This function looks for the first even number in a list and stops when it finds one.
Look at what repeats in the code.
- Primary operation: Looping through the list of numbers.
- How many times: Up to the length of the list, but may stop early.
The time to run depends on where the first even number is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Between 1 and 10 checks |
| 100 | Between 1 and 100 checks |
| 1000 | Between 1 and 1000 checks |
Pattern observation: The work grows with input size but can stop early if the answer is found.
Time Complexity: O(n)
This means the time grows roughly in proportion to the size of the input list in the worst case.
[X] Wrong: "The function always checks every number in the list."
[OK] Correct: The function stops as soon as it finds an even number, so it may check fewer items.
Understanding how loops and early exits affect time helps you explain your code clearly and choose better solutions.
"What if the function searched for all even numbers instead of stopping at the first? How would the time complexity change?"
Practice
Solution
Step 1: Understand Swift class inheritance
Swift allows classes to inherit from only one superclass, so multiple inheritance is not supported.Step 2: Evaluate other options
Swift supports functions, variables, and arithmetic operations fully, so options B, C, and D are incorrect.Final Answer:
Swift does not support multiple inheritance for classes. -> Option AQuick Check:
Multiple inheritance = Not supported [OK]
- Thinking Swift supports multiple inheritance like some other languages
- Confusing protocol inheritance with class inheritance
- Assuming Swift lacks basic features like functions or variables
Solution
Step 1: Identify safe optional unwrapping
Using 'if let' safely unwraps an optional only if it contains a value.Step 2: Check other options
print(optionalValue!) force unwraps and can crash if nil; C and D are assignments, not unwrapping.Final Answer:
if let value = optionalValue { print(value) } -> Option DQuick Check:
Safe unwrapping = if let [OK]
- Using force unwrap (!) without checking for nil
- Confusing assignment with unwrapping
- Ignoring optional safety and risking runtime crashes
let numbers = [1, 2, 3, 4]
let doubled = numbers.map { $0 * 2 }
print(doubled)Solution
Step 1: Understand the map function
The map function applies the closure to each element, multiplying each by 2.Step 2: Calculate the result
Each number doubles: 1*2=2, 2*2=4, 3*2=6, 4*2=8, so the array is [2, 4, 6, 8].Final Answer:
[2, 4, 6, 8] -> Option CQuick Check:
map doubles each element = [2, 4, 6, 8] [OK]
- Thinking map modifies the original array
- Confusing map with filter or reduce
- Expecting an error due to misunderstanding map
var name: String? print(name.count)
Solution
Step 1: Analyze optional usage
'name' is an optional String, so accessing 'count' directly is unsafe and causes an error.Step 2: Understand Swift optional rules
You must unwrap 'name' safely before accessing its properties to avoid runtime errors.Final Answer:
Optional value 'name' must be unwrapped before accessing 'count'. -> Option BQuick Check:
Access optional property = unwrap first [OK]
- Trying to access properties on optionals directly
- Ignoring the need for safe unwrapping
- Assuming optional variables behave like normal variables
Solution
Step 1: Understand the requirement
We need a dictionary with names longer than 3 characters as keys and their lengths as values.Step 2: Analyze each option
let names = ["Amy", "John", "Kate"] let dict = Dictionary(uniqueKeysWithValues: names.map { ($0, $0.count) }) includes all names, ignoring length filter. let names = ["Amy", "John", "Kate"] var dict = [String: Int]() for name in names { dict[name] = name.count } declares dict as var (mutable), but does not filter names. let names = ["Amy", "John", "Kate"] let dict = names.reduce(into: [:]) { $0[$1] = $1.count } includes all names without filtering. let names = ["Amy", "John", "Kate"] let dict = Dictionary(uniqueKeysWithValues: names.filter { $0.count > 3 }.map { ($0, $0.count) }) filters names with count > 3 before mapping to dictionary, following best practice and limitation.Final Answer:
let names = ["Amy", "John", "Kate"] let dict = Dictionary(uniqueKeysWithValues: names.filter { $0.count > 3 }.map { ($0, $0.count) }) -> Option AQuick Check:
Filter then map to dictionary = let names = ["Amy", "John", "Kate"] let dict = Dictionary(uniqueKeysWithValues: names.filter { $0.count > 3 }.map { ($0, $0.count) }) [OK]
- Not filtering names before creating dictionary
- Using mutable dictionary without filtering
- Ignoring best practice of chaining filter and map
Ready to prove it?
Pass the test and this pattern moves unknown
