Bird
Raised Fist0
Swiftprogramming~10 mins

Adding computed properties in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Adding computed properties
Define struct/class
↓
Add stored properties
↓
Add computed property with getter
↓
Access computed property
↓
Return computed value based on stored properties
This flow shows how to add a computed property that calculates a value from stored properties when accessed.
Execution Sample
Swift
struct Rectangle {
  var width: Double
  var height: Double
  var area: Double {
    return width * height
  }
}
Defines a Rectangle struct with width and height, and a computed property area that calculates width times height.
Execution Table
StepActionStored PropertiesComputed Property AccessComputed Property Result
1Create Rectangle with width=5, height=10width=5, height=10N/AN/A
2Access area propertywidth=5, height=10Calculate area = width * height50
3Change width to 7width=7, height=10N/AN/A
4Access area property againwidth=7, height=10Calculate area = width * height70
5End of executionwidth=7, height=10N/AN/A
💡 Execution ends after accessing computed property twice and changing stored property once.
Variable Tracker
VariableStartAfter Step 1After Step 3Final
widthundefined577
heightundefined101010
area (computed)undefinedN/AN/A70
Key Moments - 2 Insights
Why does the computed property 'area' change when we change 'width'?
Because 'area' calculates its value each time it is accessed using the current 'width' and 'height' values, as shown in execution_table rows 2 and 4.
Is 'area' stored in memory like 'width' and 'height'?
'area' is not stored; it is computed on demand when accessed, which is why it updates automatically without storing a separate value (see execution_table steps 2 and 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'area' after step 2?
A15
B7
C50
D10
💡 Hint
Check the 'Computed Property Result' column at step 2 in the execution_table.
At which step does the 'width' change?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Stored Properties' column to see when 'width' changes from 5 to 7.
If we changed 'height' to 20 at step 3 instead of 'width', what would 'area' be at step 4?
A100
B50
C70
D200
💡 Hint
Recall area = width * height; if width=5 and height=20, area = 5*20 = 100.
Concept Snapshot
Adding computed properties in Swift:
- Use var with a code block { get { ... } } or shorthand { ... }
- Computed properties calculate values on access, no storage
- They can use other stored properties to compute results
- Changing stored properties affects computed property output
- Useful for dynamic values like area, fullName, etc.
Full Transcript
This example shows how to add a computed property in Swift. We define a Rectangle struct with stored properties width and height. Then we add a computed property area that returns width times height. When we create a Rectangle with width 5 and height 10, accessing area returns 50. If we change width to 7, accessing area again returns 70. The computed property recalculates its value each time based on current stored properties. This means area is not stored but computed on demand. This helps keep values up to date without extra storage.

Practice

(1/5)
1. What is a computed property in Swift?
easy
A. A property that calculates a value instead of storing it.
B. A property that stores a fixed value only.
C. A property that can only be set once.
D. A property that is always optional.

Solution

  1. Step 1: Understand property types in Swift

    Stored properties hold data directly, while computed properties calculate values when accessed.
  2. Step 2: Identify computed property behavior

    Computed properties use get (and optionally set) to calculate values dynamically instead of storing them.
  3. Final Answer:

    A property that calculates a value instead of storing it. -> Option A
  4. Quick Check:

    Computed property = calculates value [OK]
Hint: Computed properties calculate values on demand, not store them [OK]
Common Mistakes:
  • Confusing computed properties with stored properties
  • Thinking computed properties always store data
  • Assuming computed properties cannot have setters
2. Which of the following is the correct syntax to add a computed property area to a struct Square that returns side * side?
easy
A. func area() -> Int { side * side }
B. var area: Int { return side * side }
C. var area: Int = side * side
D. let area = side * side

Solution

  1. Step 1: Recognize computed property syntax

    Computed properties use curly braces with a get block or implicit return inside braces.
  2. Step 2: Match syntax to the options

    var area: Int { return side * side } uses var 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.
  3. Final Answer:

    var area: Int { return side * side } -> Option B
  4. Quick Check:

    Computed property syntax = var name: Type { return value } [OK]
Hint: Use braces and return for computed properties, not direct assignment [OK]
Common Mistakes:
  • Using '=' instead of braces for computed properties
  • Defining computed property as a function
  • Using 'let' instead of 'var' for computed properties
3. What will be the output of this Swift code?
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)
medium
A. 5.0
B. Syntax error
C. 20.0
D. 10.0

Solution

  1. Step 1: Understand the computed property setter

    Setting c.diameter = 20 triggers the set block, which sets radius = newValue / 2. So radius becomes 20 / 2 = 10.
  2. Step 2: Print the updated radius

    After setting diameter, printing c.radius outputs 10.0.
  3. Final Answer:

    10.0 -> Option D
  4. Quick Check:

    Setter updates radius to 10.0 [OK]
Hint: Setter changes radius to half the diameter value [OK]
Common Mistakes:
  • Ignoring the setter and expecting radius unchanged
  • Confusing diameter and radius values
  • Assuming syntax error due to setter
4. Identify the error in this computed property code:
struct Rectangle {
    var width: Double
    var height: Double
    var area: Double {
        get { width * height }
        set { width = newValue / height }
    }
}
medium
A. width and height must be constants (let).
B. Getter must have parentheses after width * height.
C. Setter can cause division by zero if height is zero.
D. Computed properties cannot have setters.

Solution

  1. Step 1: Analyze the setter logic

    The setter divides newValue by height. If height is zero, this causes a runtime error (division by zero).
  2. Step 2: Check other options

    Getter syntax is correct without parentheses. Computed properties can have setters. Variables can be var. So only the setter can cause division by zero if height is zero.
  3. Final Answer:

    Setter can cause division by zero if height is zero. -> Option C
  4. Quick Check:

    Division by zero risk in setter = Setter can cause division by zero if height is zero. [OK]
Hint: Check for zero in divisor inside setter to avoid runtime errors [OK]
Common Mistakes:
  • Thinking getter needs parentheses
  • Believing computed properties can't have setters
  • Assuming width and height must be constants
5. You want to add a computed property 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
}
hard
A. var fullName: String { get { "\(firstName) \(lastName)" } set { let parts = newValue.split(separator: " ") if parts.count == 2 { firstName = String(parts[0]) lastName = String(parts[1]) } } }
B. var fullName: String { return "\(firstName) \(lastName)" }
C. var fullName: String { get { firstName + lastName } set { firstName = newValue } }
D. var fullName: String = ""

Solution

  1. 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.
  2. 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.
  3. 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 A
  4. Quick 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]
Hint: Use get for combining and set for splitting names [OK]
Common Mistakes:
  • Omitting the setter for fullName
  • Not splitting the input string correctly
  • Using stored property instead of computed
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard