Mobile Development Swift Subjective
Oct 04, 2025

Explain property observers in Swift.

Detailed Explanation
Property observers monitor changes to a property's value and respond accordingly.\n\n• **Types of Observers:**\n• **willSet:** Called before value is stored\n• **didSet:** Called after value is stored\n\n\nclass StepCounter { \n var totalSteps: Int = 0 {\n willSet(newTotalSteps) {\n print("About to set totalSteps to \(newTotalSteps)")\n }\n didSet {\n if totalSteps > oldValue {\n print("Added \(totalSteps - oldValue) steps")\n }\n }\n }\n}\n\nlet stepCounter = StepCounter()\nstepCounter.totalSteps = 200\n// About to set totalSteps to 200\n// Added 200 steps\n\n\n• **Use Cases:**\n• Validation before setting values\n• Triggering UI updates\n• Logging changes\n• Maintaining data consistency\n• Synchronizing related properties\n\n• **Important Notes:**\n• Cannot be used with lazy properties\n• Not called during initialization\n• Available for stored properties only\n• Can access oldValue in didSet\n• Can access newValue in willSet
Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback