Properties in Swift


Introduction to Properties in Swift

In Swift, properties are variables or constants that belong to a class, structure (struct), or enumeration (enum). They store values associated with an instance or type and provide controlled access to data. Swift properties can be categorized into stored properties and computed properties, offering flexibility and performance optimization in Swift programming.

Properties play a crucial role in memory management, encapsulation, and efficient data handling in Swift applications.

Types of Properties in Swift

Swift properties are classified into three main types:

  • Stored Properties – Hold constant or variable values inside an instance.
  • Computed Properties – Calculate values dynamically instead of storing them.
  • Property Observers – Track changes in property values.

Additionally, properties can be classified as instance properties (belonging to an object) or type properties (belonging to a type itself).

1. Stored Properties in Swift

Stored properties are the simplest form of properties, used to store constant (let) or variable (var) values in an instance of a class or struct.

struct Car {
     var brand: String
     let model: String
}

var myCar = Car(brand: "Tesla", model: "Model S")
print(myCar.brand) // Tesla

Output

Tesla

Here, brand is a variable stored property, whereas model is a constant stored property.

Lazy Stored Properties

A lazy property is initialized only when it is accessed for the first time. It is useful for expensive computations or properties that depend on external conditions.

struct DataLoader {
     lazy var data: String = loadData()

     func loadData() -> String {
         print("Loading data...")
         return "Data Loaded"
     }
}

var loader = DataLoader()
print(loader.data) // "Loading data..." → "Data Loaded"

Key Points:

  • Declared with lazy var (cannot use let).
  • Useful for performance optimization.

2. Computed Properties in Swift

Computed properties do not store values; instead, they calculate values dynamically when accessed.

struct Rectangle {
     var width: Double
     var height: Double

     var area: Double {
         return width * height
     }
}

let rect = Rectangle(width: 10, height: 5)
print(rect.area) // 50.0

Output

50.0

Computed Property with Getters and Setters

A computed property can have a getter (to return a value) and a setter (to modify another property).

struct Temperature {
     var celsius: Double

     var fahrenheit: Double {
         get {
             return (celsius * 9/5) + 32
         }
         set(newFahrenheit) {
             celsius = (newFahrenheit - 32) * 5/9
         }
     }
}

var temp = Temperature(celsius: 0)
print(temp.fahrenheit) // 32.0
temp.fahrenheit = 98.6
print(temp.celsius) // 37.0

Output

32.0
37.0

Key Points:

  • Computed properties must be declared as var (cannot be let).
  • They use get for retrieving a value and set for modifying other properties.

3. Property Observers in Swift

Property observers track changes in stored properties using willSet and didSet.

struct Account {
     var balance: Double {
         willSet(newAmount) {
             print("Balance will change to \(newAmount)")
         }
         didSet {
             print("Balance changed from \(oldValue) to \(balance)")
         }
     }
}

var myAccount = Account(balance: 1000)
myAccount.balance = 1200

Output

Balance will change to 1200.0
Balance changed from 1000.0 to 1200.0

Key Points:

  • willSet runs before the value changes.
  • didSet runs after the value changes.
  • Useful for tracking modifications.

4. Type Properties (Static Properties) in Swift

Type properties belong to the type itself, rather than an instance. They are declared using the static or class keyword.

struct Database {
     static var maxConnections = 10
}

print(Database.maxConnections) // 10

If used in a class and you want subclassing, use class instead of static.

class Config {
     class var theme: String {
         return "Dark Mode"
     }
}

print(Config.theme) // "Dark Mode"

Output

10
Dark Mode

5. Access Control in Properties

Swift allows you to control property access using access modifiers.

Modifier Description
private Access restricted to the same class or struct
fileprivate Access restricted to the same file
internal (default) Access within the same module
public Access outside the module
open Similar to public but allows subclassing

class User {
     private var password: String = "12345"
}

let user = User()
// user.password // ❌ Error: Cannot access private property

6. Property Wrappers in Swift

Property wrappers add extra logic to properties, such as validation or data persistence.

@propertyWrapper
struct Capitalized {
     private var text: String = ""

     var wrappedValue: String {
         get { text }
         set { text = newValue.capitalized }
     }
}

struct UserProfile {
     @Capitalized var username: String
}

var user = UserProfile(username: "john doe")
print(user.username) // "John Doe"

Output

"John Doe"

Key Points:

  • Wrappers enhance property behavior.
  • Used for validation, caching, or transformation.

Best Practices for Using Properties in Swift


  • Use computed properties to avoid unnecessary storage.
  • Use property observers to track changes efficiently.
  • Prefer lazy properties for expensive computations.
  • Use type properties (static) for shared values.
  • Apply access control to protect sensitive data.
  • Leverage property wrappers for reusability.

Conclusion

Properties in Swift provide powerful data encapsulation, memory management, and performance optimization. By using stored properties, computed properties, property observers, type properties, and property wrappers, developers can write more efficient, readable, and maintainable Swift code.

Understanding how to properly implement Swift properties is key to building scalable and high-performance iOS/macOS applications.