Classes,Properties and Methods in Swift

Understanding Properties in Swift

Properties associate values with a particular class, structure, or enumeration. Swift provides two kinds of properties: stored properties and computed properties.

Stored Properties

Stored properties store constant and variable values as part of an instance. In its simplest form, a stored property is a variable or constant that is stored directly as part of an instance. For example, a Person class might have a name and an age stored property.

class Person { var name: String var age: Int }

Computed Properties

Unlike stored properties, computed properties do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.

class Square { var sideLength: Double var area: Double { get { return sideLength * sideLength } set { sideLength = sqrt(newValue) } } }

In this example, area is a computed property that calculates the area of a square based on its sideLength.

Property Observers

Swift provides a powerful feature called property observers that allows you to observe and respond to changes in a property’s value. Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value.

There are two types of property observers in Swift: willSet and didSet.

class StepCounter { var totalSteps: Int = 0 { willSet(newTotalSteps) { print("About to set totalSteps to \(newTotalSteps)") } didSet { if totalSteps > oldValue { print("Added \(totalSteps - oldValue) steps") } } } }

Static Properties

Static properties are properties that belong to the type itself, not to any one instance of that type. There can only be one copy of these properties, no matter how many instances of that type you create.

class SomeClass { static var storedTypeProperty = "Some value." static var computedTypeProperty: Int { return 1 } }

In conclusion, properties in Swift are powerful and flexible. They allow you to add additional functionality to your value storage and provide hooks to monitor when values are set, and to compute values on the fly.