Use Properties in Swift
Written by Team Kodeco
Properties in Swift are used to store values associated with an instance of a class or structure. They can be either stored properties, which hold a value, or computed properties, which calculate a value.
Defining a Stored Property
Here’s an example of how to define a stored property in a class:
class MyClass {
var myStoredProperty: Int = 0
}
This creates a new class called MyClass
with a stored property called myStoredProperty
that is initialized with the value 0.
You can access and modify the value of a stored property like this:
let myObject = MyClass()
myObject.myStoredProperty = 10
print(myObject.myStoredProperty) // prints "10"
Defining a Computed Property
In Swift, computed properties are properties that don’t have a stored value, but instead provide a getter and an optional setter to compute their value. The general syntax for defining a computed property is as follows:
var myComputedProperty: SomeType {
get {
// code to compute the value of the property
}
set(newValue) {
// code to set the value of the property
}
}
The get
keyword is used to define the code that is executed when the property is read and the set
keyword is used to define the code that is executed when the property is written to.
Here’s an example of how to define a computed property in a class:
class MyClass {
var myStoredProperty: Int = 0
var myComputedProperty: Int {
get {
return myStoredProperty * 2
}
set {
myStoredProperty = newValue / 2
}
}
}
This creates a new class called MyClass
with a computed property called myComputedProperty
that returns the value of myStoredProperty
multiplied by 2.
You can access the value of a computed property just like you would with a stored property:
let myObject = MyClass()
myObject.myStoredProperty = 10
print(myObject.myComputedProperty) // prints "20"
It’s also possible to set the value of a computed property, which will call the setter and use the value in it:
myObject.myComputedProperty = 30
print(myObject.myStoredProperty) // prints "15"