0
0
Swiftprogramming~10 mins

Property observers (willSet, didSet) in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a property observer that runs before the value changes.

Swift
var score: Int = 0 {
    [1] {
        print("Score will change to \(newValue)")
    }
}
Drag options to blanks, or click blank then click option'
Aget
BdidSet
Cset
DwillSet
Attempts:
3 left
💡 Hint
Common Mistakes
Using didSet instead of willSet, which runs after the value changes.
2fill in blank
medium

Complete the code to print the old value after the property changes.

Swift
var level: Int = 1 {
    didSet {
        print("Level changed from \([1]) to \(level)")
    }
}
Drag options to blanks, or click blank then click option'
AoldValue
Blevel
CnewValue
Dself
Attempts:
3 left
💡 Hint
Common Mistakes
Using newValue inside didSet, which is not available there.
3fill in blank
hard

Fix the error in the property observer to correctly access the new value.

Swift
var health: Int = 100 {
    willSet {
        print("Health will be set to \([1])")
    }
}
Drag options to blanks, or click blank then click option'
AoldValue
BnewValue
Cself
Dhealth
Attempts:
3 left
💡 Hint
Common Mistakes
Using oldValue or the property name instead of newValue in willSet.
4fill in blank
hard

Fill both blanks to create a property observer that prints old and new values.

Swift
var temperature: Double = 20.0 {
    willSet {
        print("Temperature will change from \([1]) to \([2])")
    }
}
Drag options to blanks, or click blank then click option'
Atemperature
BoldValue
CnewValue
Dself
Attempts:
3 left
💡 Hint
Common Mistakes
Using oldValue in willSet, which is not available.
5fill in blank
hard

Fill all three blanks to create a didSet observer that prints old and new values and updates a label.

Swift
var progress: Int = 0 {
    didSet {
        print("Progress changed from \([1]) to \([2])")
        progressLabel.text = "Progress: \([3])%"
    }
}
Drag options to blanks, or click blank then click option'
AoldValue
Bprogress
DnewValue
Attempts:
3 left
💡 Hint
Common Mistakes
Using newValue inside didSet, which is not available.