Bird
Raised Fist0
Swiftprogramming~20 mins

Adding computed properties in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Computed Properties Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Swift code with a computed property?
Consider the following Swift struct with a computed property. What will be printed when the code runs?
Swift
struct Rectangle {
    var width: Double
    var height: Double
    var area: Double {
        return width * height
    }
}

let rect = Rectangle(width: 3, height: 4)
print(rect.area)
A7.0
B0.0
C12.0
DError: Cannot access computed property
Attempts:
2 left
💡 Hint
Remember that computed properties calculate their value when accessed.
❓ Predict Output
intermediate
2:00remaining
What is the value of the computed property after changing stored properties?
Given this Swift class with a computed property, what will be printed after modifying the stored properties?
Swift
class Circle {
    var radius: Double
    var diameter: Double {
        return radius * 2
    }
    init(radius: Double) {
        self.radius = radius
    }
}

let circle = Circle(radius: 5)
print(circle.diameter)
circle.radius = 7
print(circle.diameter)
A10.0 and 14.0
B10.0 and 10.0
C5.0 and 7.0
DError: Cannot modify radius
Attempts:
2 left
💡 Hint
Computed properties reflect the current state of stored properties.
🔧 Debug
advanced
2:00remaining
Why does this computed property cause a compile-time error?
Examine the Swift struct below. Why does accessing the computed property cause a compile-time error?
Swift
struct Counter {
    var count: Int = 0
    mutating var nextCount: Int {
        count += 1
        return count
    }
}

var counter = Counter()
print(counter.nextCount)
AComputed properties cannot return Int values
BCannot modify 'count' inside a computed property without 'mutating' keyword
CMissing return statement in computed property
DStructs cannot have computed properties
Attempts:
2 left
💡 Hint
Think about mutability rules in Swift structs.
📝 Syntax
advanced
2:00remaining
Which option correctly defines a read-write computed property in Swift?
Choose the correct syntax for a computed property that can be read and written to.
A
var temperature: Double {
    get {
        return celsius
    }
}
B
var temperature: Double = {
    return celsius
}
C
var temperature: Double {
    return celsius
    set {
        celsius = newValue
    }
}
D
var temperature: Double {
    get {
        return celsius
    }
    set {
        celsius = newValue
    }
}
Attempts:
2 left
💡 Hint
A read-write computed property needs both get and set blocks properly defined.
🚀 Application
expert
2:00remaining
How many times is the computed property evaluated in this Swift code?
Consider this Swift code. How many times will the computed property 'description' be evaluated during execution?
Swift
struct Person {
    var firstName: String
    var lastName: String
    var description: String {
        print("Computing description")
        return "\(firstName) \(lastName)"
    }
}

let person = Person(firstName: "Jane", lastName: "Doe")
print(person.description)
print(person.description)
A2 times
B1 time
C0 times
D3 times
Attempts:
2 left
💡 Hint
Each access to a computed property runs its code.

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