Getters and Setters in Swift

Getters and Setters in Swift

In Swift, properties are fundamental constructs used to store and retrieve values associated with a particular instance of a type. While stored properties hold constant or variable values directly, computed properties do not store values themselves but instead provide a mechanism to calculate values on-the-fly. Computed properties can have custom getters and setters, enabling developers to implement custom behavior when accessing or modifying these properties. This article delves into the concept of computed properties with custom getters and setters in Swift, exploring their syntax, usage, and benefits.

Computed Properties Overview:
Computed properties in Swift allow developers to define custom logic for getting and setting values associated with a property. Unlike stored properties, which store values directly, computed properties do not store values themselves but rather compute their value using a getter (for retrieval) and optionally a setter (for modification). Computed properties are declared with the var keyword, and they do not have an associated storage location.

Syntax of Computed Properties:
The syntax for declaring computed properties in Swift involves defining a pair of braces {} after the property declaration. Within these braces, developers can specify a getter block to compute the property's value and, if needed, a setter block to handle property assignments.

Example:

struct Circle {
    var radius: Double
    
    // Computed property for calculating the area of the circle
    var area: Double {
        return Double.pi * radius * radius
    }
}

In this example, the area property of the Circle struct is a computed property that calculates the area of the circle based on its radius. Whenever the area property is accessed, the getter block is executed to compute and return the area value.

Custom Getters and Setters:
Computed properties can have custom getters and setters, allowing developers to define custom behavior for property access and assignment. The getter block is responsible for computing and returning the property's value, while the setter block is invoked when the property is assigned a new value. Developers can leverage custom getters and setters to implement validation logic, perform side effects, or synchronize property values with other parts of the code.

Example with Custom Getter and Setter:

struct Temperature {
    private var celsius: Double
    
    // Computed property with custom getter and setter for Fahrenheit conversion
    var fahrenheit: Double {
        get {
            return celsius * 9 / 5 + 32
        }
        set {
            celsius = (newValue - 32) * 5 / 9
        }
    }
    
    // Initializer
    init(celsius: Double) {
        self.celsius = celsius
    }
}

// Usage
var temperature = Temperature(celsius: 25)
print(temperature.fahrenheit) // Output: 77.0
temperature.fahrenheit = 68
print(temperature.celsius)    // Output: 20.0

In this example, the Temperature struct defines a computed property fahrenheit with a custom getter and setter. The getter computes the temperature in Fahrenheit based on the stored Celsius value, while the setter converts Fahrenheit to Celsius and updates the stored value accordingly.

Usage:

  • celsius is a stored property representing the temperature in Celsius.
  • fahrenheit is a computed property with a custom getter and setter. The getter calculates the temperature in Fahrenheit based on the stored Celsius value, while the setter converts Fahrenheit to Celsius and updates the stored value accordingly.
  • The init method initializes the Temperature struct with a temperature value in Celsius.
  • The usage demonstrates accessing the fahrenheit property, which triggers the custom getter, and also setting the fahrenheit property, which triggers the custom setter.

Benefits of Computed Properties with Custom Getters and Setters:

  1. Encapsulation: Computed properties with custom getters and setters enable encapsulation of property access and modification logic within the type definition itself, promoting clean and maintainable code.
  2. Flexibility: Developers have the flexibility to implement custom behavior for property access and assignment, allowing for validation, conversion, or synchronization tasks.
  3. Abstraction: Custom getters and setters abstract away the underlying implementation details of property access and assignment, providing a clear interface for interacting with the property.


Computed properties with custom getters and setters are powerful constructs in Swift, offering a flexible and encapsulated mechanism for defining property access and modification behavior. By leveraging custom getters and setters, developers can implement complex logic, validation, or conversion tasks while maintaining a clean and expressive codebase. Understanding and effectively utilizing computed properties with custom getters and setters is essential for building robust and maintainable Swift applications.