Sobes.tech
Junior

What does it mean if a variable has a setter?

sobes.tech AI

Answer from AI

A setter is a method that allows controlling the assignment of a new value to a variable. When a setter is used, the standard assignment mechanism is replaced with code inside the setter. This provides the ability to:

  • Validate input data: Check if the new value meets certain conditions before assigning it to the variable.
    var age: Int = 0 {
        didSet { // didSet is called after the value is set
            if age < 0 {
                age = 0 // Prevent assigning a negative value
            }
        }
    }
    
  • Perform additional actions: Run other code when the variable's value changes, such as updating the user interface or notifying other parts of the application.
    var score: Int = 0 {
        didSet { // didSet
            print("Score updated to \(score)") // Log the change
            updateUI() // Update UI
        }
    }
    
    func updateUI() {
        // Code to update the interface
    }
    
  • Calculate other property values: Changing one property can affect the value of another.
    var radius: Double = 0.0 {
        didSet { // didSet
            area = Double.pi * radius * radius // Recalculate area when radius changes
        }
    }
    
    var area: Double = 0.0 // Property dependent on radius
    

In Swift, setters can be used for stored properties and computed properties. For stored properties, property observers (willSet and didSet) are often used, which are called before and after the new value is set, respectively. For computed properties, the setter (set) defines how the value should be assigned.

var myProperty: String {
    // Getter
    get {
        return "Value is: \(internalValue)"
    }
    // Setter
    set(newValue) {
        internalValue = newValue + " processed" // Modify the assigned value
    }
}

private var internalValue: String = "" // Internal stored property
What does it mean if a variable has a setter? — iOS - sobes.tech