Creating a struct Instance
After defining the struct type, you can create a struct instance by calling the constructor of struct. You can also call the constructor by the struct type name outside the struct definition. The following example defines an r variable of the Rectangle type.
let r = Rectangle(10, 20)
After the struct instance is created, you can access the member variables and member functions that are modified by a visibility modifier (such as public) through the instance. In the following example, r.width and r.height can access the values of width and height in r, and r.area() can call the member function area of r.
let r = Rectangle(10, 20)
let width = r.width // width = 10
let height = r.height // height = 20
let a = r.area() // a = 200
If you want to change the value of a member variable through a struct instance, use var to define both the variables of the struct type and the modified member variables as mutable variables. For example:
struct Rectangle {
public var width: Int64
public var height: Int64
public init(width: Int64, height: Int64) {
this.width = width
this.height = height
}
public func area() {
width * height
}
}
main() {
var r = Rectangle(10, 20) // r.width = 10, r.height = 20
r.width = 8 // r.width = 8
r.height = 24 // r.height = 24
let a = r.area() // a = 192
}
When a value is assigned or a parameter is passed, the struct instance is copied to generate a new instance. (If the member variable is of the reference type, only the reference is copied, while the referenced object is not.) The modification of either instance does not affect the other. As described in the following example, after r1 is assigned to r2, changing the values of width and height in r1 does not affect those in r2.
struct Rectangle {
public var width: Int64
public var height: Int64
public init(width: Int64, height: Int64) {
this.width = width
this.height = height
}
public func area() {
width * height
}
}
main() {
var r1 = Rectangle(10, 20) // r1.width = 10, r1.height = 20
var r2 = r1 // r2.width = 10, r2.height = 20
r1.width = 8 // r1.width = 8
r1.height = 24 // r1.height = 24
let a1 = r1.area() // a1 = 192
let a2 = r2.area() // a2 = 200
}