Adding computed properties in Swift - Time & Space Complexity
When we add computed properties in Swift, we want to know how much extra work the program does as it runs.
We ask: How does the time to get the computed property change when the input changes?
Analyze the time complexity of the following code snippet.
struct Numbers {
var values: [Int]
var sum: Int {
var total = 0
for num in values {
total += num
}
return total
}
}
This code defines a computed property sum that adds all numbers in an array each time it is accessed.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the
valuesarray to add each number. - How many times: Once for every element in the array each time
sumis accessed.
As the array gets bigger, the time to calculate sum grows because it adds more numbers.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items; doubling items doubles the work.
Time Complexity: O(n)
This means the time to get the computed property grows in a straight line with the size of the array.
[X] Wrong: "Accessing a computed property is always fast and constant time."
[OK] Correct: Computed properties run code each time, so if they loop over data, the time depends on the data size.
Understanding how computed properties affect time helps you write clear and efficient code, a skill valued in many coding challenges.
What if we stored the sum in a variable and updated it only when the array changes? How would the time complexity of accessing the sum change?
Practice
Solution
Step 1: Understand property types in Swift
Stored properties hold data directly, while computed properties calculate values when accessed.Step 2: Identify computed property behavior
Computed properties useget(and optionallyset) to calculate values dynamically instead of storing them.Final Answer:
A property that calculates a value instead of storing it. -> Option AQuick Check:
Computed property = calculates value [OK]
- Confusing computed properties with stored properties
- Thinking computed properties always store data
- Assuming computed properties cannot have setters
area to a struct Square that returns side * side?Solution
Step 1: Recognize computed property syntax
Computed properties use curly braces with agetblock or implicit return inside braces.Step 2: Match syntax to the options
var area: Int { return side * side } usesvar area: Int { return side * side }, which is correct for a computed property. var area: Int = side * side tries to assign directly, which is invalid for computed properties.Final Answer:
var area: Int { return side * side } -> Option BQuick Check:
Computed property syntax = var name: Type { return value } [OK]
- Using '=' instead of braces for computed properties
- Defining computed property as a function
- Using 'let' instead of 'var' for computed properties
struct Circle {
var radius: Double
var diameter: Double {
get { radius * 2 }
set { radius = newValue / 2 }
}
}
var c = Circle(radius: 5)
c.diameter = 20
print(c.radius)Solution
Step 1: Understand the computed property setter
Settingc.diameter = 20triggers thesetblock, which setsradius = newValue / 2. So radius becomes 20 / 2 = 10.Step 2: Print the updated radius
After setting diameter, printingc.radiusoutputs 10.0.Final Answer:
10.0 -> Option DQuick Check:
Setter updates radius to 10.0 [OK]
- Ignoring the setter and expecting radius unchanged
- Confusing diameter and radius values
- Assuming syntax error due to setter
struct Rectangle {
var width: Double
var height: Double
var area: Double {
get { width * height }
set { width = newValue / height }
}
}Solution
Step 1: Analyze the setter logic
The setter dividesnewValuebyheight. Ifheightis zero, this causes a runtime error (division by zero).Step 2: Check other options
Getter syntax is correct without parentheses. Computed properties can have setters. Variables can bevar. So only the setter can cause division by zero if height is zero.Final Answer:
Setter can cause division by zero if height is zero. -> Option CQuick Check:
Division by zero risk in setter = Setter can cause division by zero if height is zero. [OK]
- Thinking getter needs parentheses
- Believing computed properties can't have setters
- Assuming width and height must be constants
fullName to this struct that combines firstName and lastName with a space, and also allows setting both names by splitting the input string. Which code correctly implements this?struct Person {
var firstName: String
var lastName: String
// Add fullName computed property here
}Solution
Step 1: Understand the requirements
The computed property must combine first and last names with a space in the getter, and split the input string to set both names in the setter.Step 2: Evaluate each option
var fullName: String { get { "\(firstName) \(lastName)" } set { let parts = newValue.split(separator: " ") if parts.count == 2 { firstName = String(parts[0]) lastName = String(parts[1]) } } } correctly implements a getter returning "firstName lastName" and a setter splitting the input string into two parts to assign firstName and lastName. var fullName: String { return "\(firstName) \(lastName)" } lacks a setter. var fullName: String { get { firstName + lastName } set { firstName = newValue } } concatenates without space and sets only firstName. var fullName: String = "" is a stored property, not computed.Final Answer:
var fullName: String { get { "\(firstName) \(lastName)" } set { let parts = newValue.split(separator: " ") if parts.count == 2 { firstName = String(parts[0]) lastName = String(parts[1]) } } } -> Option AQuick Check:
Computed property with get and set splitting string = var fullName: String { get { "\(firstName) \(lastName)" } set { let parts = newValue.split(separator: " ") if parts.count == 2 { firstName = String(parts[0]) lastName = String(parts[1]) } } } [OK]
- Omitting the setter for fullName
- Not splitting the input string correctly
- Using stored property instead of computed
Ready to prove it?
Pass the test and this pattern moves unknown
