Closure expression syntax in Swift - Time & Space Complexity
Let's see how the time it takes to run a closure expression changes as the input grows.
We want to know how the number of operations grows when using closure expressions in Swift.
Analyze the time complexity of the following code snippet.
let numbers = [1, 2, 3, 4, 5]
let doubled = numbers.map { (number: Int) -> Int in
return number * 2
}
print(doubled)
This code uses a closure expression inside the map function to double each number in the array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The closure runs once for each element in the array.
- How many times: Exactly as many times as there are elements in
numbers.
Each element causes the closure to run once, so the total work grows with the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 closure calls |
| 100 | 100 closure calls |
| 1000 | 1000 closure calls |
Pattern observation: The work grows directly in proportion to the input size.
Time Complexity: O(n)
This means the time to run the closure grows linearly with the number of items in the array.
[X] Wrong: "The closure runs only once no matter the array size."
[OK] Correct: The closure is called for each element, so more elements mean more calls.
Understanding how closures run over collections helps you explain performance clearly in real coding situations.
What if we replaced map with filter using a closure? How would the time complexity change?
Practice
Solution
Step 1: Understand the definition of closure
A closure is a block of code that can be saved and run later, similar to a function but more flexible.Step 2: Compare options with closure meaning
Only 'A block of code that can be passed around and executed later' correctly describes a closure.Final Answer:
A block of code that can be passed around and executed later -> Option BQuick Check:
Closure = block of code passed and run later [OK]
- Confusing closures with variables
- Thinking closures are loops
- Mixing closures with function keywords
Solution
Step 1: Identify closure syntax components
A closure with parameters and return type uses parentheses for parameters, '->' for return type, and 'in' before the code.Step 2: Check each option
{ (a: Int, b: Int) -> Int in return a + b } correctly uses (a: Int, b: Int) -> Int in return a + b. { a, b in a + b } omits types and requires context for type inference to compile. func sum(a: Int, b: Int) -> Int { return a + b } is a function, not a closure. { (a, b) -> Int { a + b } } has wrong braces placement and misses 'in'.Final Answer:
{ (a: Int, b: Int) -> Int in return a + b } -> Option DQuick Check:
Closure syntax = parameters, return type, in keyword [OK]
- Confusing functions with closures
- Missing 'in' keyword
- Incorrect braces placement
let multiply = { (x: Int, y: Int) -> Int in x * y }
print(multiply(3, 4))Solution
Step 1: Understand closure definition and call
The closure multiply takes two Ints and returns their product (x * y). It is called with 3 and 4.Step 2: Calculate the result
3 * 4 = 12, so print outputs 12.Final Answer:
12 -> Option AQuick Check:
3 times 4 = 12 [OK]
- Adding instead of multiplying
- Concatenating numbers as strings
- Syntax errors in closure call
let greet = { name: String in
print("Hello, \(name)!")
}Solution
Step 1: Check closure parameter syntax
Closure parameters must be enclosed in parentheses, like (name: String).Step 2: Identify the error in given code
The code uses 'name: String' without parentheses, which is invalid syntax.Final Answer:
Parameters must be in parentheses -> Option AQuick Check:
Closure parameters need parentheses [OK]
- Omitting parentheses around parameters
- Forgetting 'in' keyword
- Thinking closures can't print
let numbers = [1, 2, 3, 4]
let doubled = numbers.map({ (num: Int) -> Int in return num * 2 })
print(doubled)Solution
Step 1: Understand closure simplification rules
Swift allows removing parameter types and 'return' when the closure is a single expression, and using shorthand $0 for first parameter.Step 2: Apply shorthand argument names
Replacing full closure with numbers.map { $0 * 2 } simplifies code and is correct.Final Answer:
Use shorthand argument names: numbers.map { $0 * 2 } -> Option CQuick Check:
Shorthand $0 replaces explicit parameters [OK]
- Keeping full syntax unnecessarily
- Thinking closures can't be simplified
- Replacing map with loops unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
