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 its member variables (modified by public
) and member functions through it. In the following example, r.width
and r.height
can be used to access the values of width
and height
in r
, and r.area()
can be used to 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. The modification of one 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
}