Properties
Use var and let statements to declare variable and constant properties.
self is a special predefined property, that refers to the current object within a class or structure.
super is a special predefined property, that refers to the parent class. Typically it is used for overriding methods in subclasses.
struct FixedLengthRange {
var firstValue: Int
let length: Int
init(name: String, breed: String) {
self.firstValue = firstValue
self.length = length
}
}
You can initialize properties in declaration or in the special method init() called initializer (constructor in other languages). Read more about initialization.
struct A {
var a = 1.0
var b: Double
init{
b=2.0
}
}
A lazy stored property is a property whose initial value isn’t calculated until the first time it’s used.
class DataManager {
lazy var importer = DataImporter()
var data: [String] = []
// ...
}
You can provide a getter and an optional setter to retrieve and set other properties and values indirectly. Such properties are called computed properties.
struct Rect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set(newCenter) {
origin.x = newCenter.x - (size.width / 2)
origin.y = newCenter.y - (size.height / 2)
}
}
}
You can add property observers.
class StepCounter {
var totalSteps: Int = 0 {
willSet(newTotalSteps) {
print("About to set totalSteps to \(newTotalSteps)")
}
didSet {
if totalSteps > oldValue {
print("Added \(totalSteps - oldValue) steps")
}
}
}
}
property wrapper
A property wrapper adds a layer of separation between code that manages how a property is stored and the code that defines a property.
@propertyWrapper
struct TwelveOrLess {
private var number = 0
var wrappedValue: Int {
get { return number }
set { number = min(newValue, 12) }
}
}
struct SmallRectangle {
@TwelveOrLess var height: Int
@TwelveOrLess var width: Int
}
var rectangle = SmallRectangle()
print(rectangle.height)
// Prints "0"
rectangle.height = 10
print(rectangle.height)
// Prints "10"
rectangle.height = 24
print(rectangle.height)
// Prints "12"