Bird
Raised Fist0
Swiftprogramming~20 mins

Property observers (willSet, didSet) in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Property Observer 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 using willSet?
Consider this Swift code with a property observer willSet. What will be printed when score is set to 10?
Swift
class Game {
    var score: Int = 0 {
        willSet {
            print("Score will change from \(score) to \(newValue)")
        }
    }
}

let game = Game()
game.score = 10
AScore will change from 10 to 0
BScore will change from 0 to 10
CScore will change from 0 to 0
DNo output
Attempts:
2 left
💡 Hint
Remember that willSet runs before the property value changes, and newValue holds the new value.
❓ Predict Output
intermediate
2:00remaining
What is printed by this Swift code using didSet?
Look at this Swift code with a didSet observer. What will be printed after setting temperature to 30?
Swift
struct Weather {
    var temperature: Int = 20 {
        didSet {
            print("Temperature changed from \(oldValue) to \(temperature)")
        }
    }
}

var today = Weather()
today.temperature = 30
ATemperature changed from 20 to 30
BTemperature changed from 30 to 20
CTemperature changed from 20 to 20
DNo output
Attempts:
2 left
💡 Hint
didSet runs after the property value changes, and oldValue holds the previous value.
🔧 Debug
advanced
2:30remaining
Why does this Swift code cause a runtime error?
This Swift code uses didSet to update the property. Why does it crash when setting value to 5?
Swift
class Counter {
    var value: Int = 0 {
        didSet {
            value = 10
        }
    }
}

let counter = Counter()
counter.value = 5
AIt causes infinite recursion because didSet sets value again inside didSet.
BIt causes a syntax error because didSet cannot modify the property.
CIt causes a compile-time error because value is a constant.
DIt runs fine and sets value to 5 without error.
Attempts:
2 left
💡 Hint
Think about what happens when you assign to the property inside didSet.
🧠 Conceptual
advanced
2:00remaining
Which statement about willSet and didSet is true?
Choose the correct statement about Swift's property observers willSet and didSet:
AwillSet runs after the property value changes, and didSet runs before the change.
BwillSet provides the old value as newValue, and didSet provides the new value as oldValue.
CBoth willSet and didSet run only when the property is initialized.
DwillSet runs before the property value changes, and didSet runs after the change.
Attempts:
2 left
💡 Hint
Think about the timing of these observers relative to the property change.
❓ Predict Output
expert
3:00remaining
What is the final output of this Swift code with nested property observers?
Analyze this Swift code with two properties having observers. What will be printed after setting outer.value to 3?
Swift
class Inner {
    var value: Int = 0 {
        willSet {
            print("Inner willSet: \(value) -> \(newValue)")
        }
        didSet {
            print("Inner didSet: \(oldValue) -> \(value)")
        }
    }
}

class Outer {
    var value: Int = 0 {
        willSet {
            print("Outer willSet: \(value) -> \(newValue)")
        }
        didSet {
            print("Outer didSet: \(oldValue) -> \(value)")
            inner.value = value * 2
        }
    }
    var inner = Inner()
}

let outer = Outer()
outer.value = 3
A
Inner willSet: 0 -> 6
Inner didSet: 0 -> 6
Outer willSet: 0 -> 3
Outer didSet: 0 -> 3
B
Outer willSet: 0 -> 3
Inner willSet: 0 -> 6
Outer didSet: 0 -> 3
Inner didSet: 0 -> 6
C
Outer willSet: 0 -> 3
Outer didSet: 0 -> 3
Inner willSet: 0 -> 6
Inner didSet: 0 -> 6
D
Outer didSet: 0 -> 3
Outer willSet: 0 -> 3
Inner didSet: 0 -> 6
Inner willSet: 0 -> 6
Attempts:
2 left
💡 Hint
Remember the order: willSet runs before the property changes, didSet after. Also, didSet of outer triggers inner.value change.

Practice

(1/5)
1. What does the willSet property observer do in Swift?
easy
A. It runs code after the property value changes.
B. It runs code just before the property value changes.
C. It prevents the property value from changing.
D. It initializes the property with a default value.

Solution

  1. Step 1: Understand the role of willSet

    willSet runs code right before the property value changes.
  2. Step 2: Compare with didSet

    didSet runs code after the value changes, so it is different from willSet.
  3. Final Answer:

    It runs code just before the property value changes. -> Option B
  4. Quick Check:

    willSet = before change [OK]
Hint: willSet runs before change, didSet runs after [OK]
Common Mistakes:
  • Confusing willSet with didSet
  • Thinking willSet stops the change
  • Assuming willSet initializes the property
2. Which of the following is the correct syntax to add a didSet observer to a Swift property score?
easy
A. var score: Int { didSet { print("Score changed") } }
B. var score: Int = 0 didSet { print("Score changed") }
C. var score: Int = 0 { didSet { print("Score changed") } }
D. var score: Int didSet { print("Score changed") }

Solution

  1. Step 1: Recall property observer syntax

    Property observers must be inside braces after property declaration with initial value.
  2. Step 2: Check each option

    var score: Int = 0 { didSet { print("Score changed") } } correctly declares score with initial value and braces containing didSet.
  3. Final Answer:

    var score: Int = 0 { didSet { print("Score changed") } } -> Option C
  4. Quick Check:

    Correct syntax uses braces after initial value [OK]
Hint: Use braces after initial value for observers [OK]
Common Mistakes:
  • Missing braces around didSet block
  • No initial value for stored property
  • Placing didSet outside property declaration
3. What will be printed when the following Swift code runs?
class Counter {
    var count: Int = 0 {
        willSet {
            print("About to set count to \(newValue)")
        }
        didSet {
            print("Count changed from \(oldValue) to \(count)")
        }
    }
}

let counter = Counter()
counter.count = 5
medium
A. About to set count to 5 Count changed from 0 to 5
B. Count changed from 0 to 5 About to set count to 5
C. About to set count to 0 Count changed from 0 to 5
D. Count changed from 5 to 0 About to set count to 5

Solution

  1. Step 1: Understand willSet and didSet order

    willSet runs before the value changes, printing the new value. didSet runs after, printing old and new values.
  2. Step 2: Trace the code execution

    Setting count to 5 triggers willSet printing "About to set count to 5", then didSet printing "Count changed from 0 to 5".
  3. Final Answer:

    About to set count to 5 Count changed from 0 to 5 -> Option A
  4. Quick Check:

    willSet before, didSet after change [OK]
Hint: willSet prints newValue, didSet prints oldValue and new value [OK]
Common Mistakes:
  • Mixing order of willSet and didSet prints
  • Confusing oldValue and newValue
  • Ignoring that willSet runs before assignment
4. Identify the error in this Swift code using property observers:
struct Temperature {
    var celsius: Double {
        willSet(newTemp) {
            print("Temperature will change to \(newTemp)")
        }
        didSet {
            print("Temperature changed from \(oldValue) to \(celsius)")
        }
    }
}

var temp = Temperature(celsius: 25)
temp.celsius = 30
medium
A. Property observers cannot be used in structs.
B. The willSet parameter name cannot be custom like newTemp.
C. The struct cannot be instantiated with an initial value.
D. Stored property must have an initial value or be optional.

Solution

  1. Step 1: Check property declaration rules

    Stored properties in structs must have initial values or be optional unless initialized in init.
  2. Step 2: Analyze the code

    Property celsius has no initial value and no initializer, causing error.
  3. Final Answer:

    Stored property must have an initial value or be optional. -> Option D
  4. Quick Check:

    Stored properties need initial values [OK]
Hint: Stored properties need initial values or init [OK]
Common Mistakes:
  • Thinking willSet parameter name is invalid
  • Assuming property observers disallowed in structs
  • Ignoring missing initial value error
5. You want to track changes to a user's age property and prevent it from being set to a value less than the current age. Which approach using property observers is correct?
hard
A. Use didSet to check if age decreased and reset it back to oldValue.
B. Use willSet to check newValue and revert if less than current age.
C. Use willSet to prevent assignment by throwing an error.
D. Use didSet to print a message but allow any change.

Solution

  1. Step 1: Understand property observer capabilities

    Property observers cannot prevent assignment in willSet; they run before or after change but cannot stop it.
  2. Step 2: Choose correct way to revert invalid change

    In didSet, you can detect invalid changes and reset the property back to oldValue to prevent decrease.
  3. Final Answer:

    Use didSet to check if age decreased and reset it back to oldValue. -> Option A
  4. Quick Check:

    didSet can revert changes, willSet cannot prevent them [OK]
Hint: Use didSet to revert invalid changes, willSet can't stop assignment [OK]
Common Mistakes:
  • Trying to prevent assignment in willSet
  • Assuming willSet can throw errors
  • Not resetting property in didSet after invalid change
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