๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

Swift Structures

A structure is a type that groups named values of its own into one value. Each named value inside it is called a property.

Making a point

The Point struct holds two properties named x and y. The memberwise initializer fills both properties in order.

struct Point {
    var x: Int
    var y: Int
}
let point = Point(x: 3, y: 4)
print(point.x)
print(point.y)

Changing one property

The point is made with var, so its x property can take a new value. The y property keeps its first value.

struct Point {
    var x: Int
    var y: Int
}
var point = Point(x: 3, y: 4)
point.x = 10
print(point.x)
print(point.y)

A method inside the struct

The sum method adds the two properties of its own value. The call prints the total for the point with x 3 and y 4.

struct Point {
    var x: Int
    var y: Int
    func sum() -> Int {
        return x + y
    }
}
let point = Point(x: 3, y: 4)
print(point.sum())

A mutating method

The bump method carries the mutating mark because it changes the count property. Two calls raise the count from 0 to 2.

struct Counter {
    var count: Int
    mutating func bump() {
        count += 1
    }
}
var counter = Counter(count: 0)
counter.bump()
counter.bump()
print(counter.count)

A copy changes on its own

The second point starts as a copy of the first point. Changing the copy leaves the first point at 3, and the two printed numbers prove it.

struct Point {
    var x: Int
    var y: Int
}
let first = Point(x: 3, y: 4)
var second = first
second.x = 99
print(first.x)
print(second.x)

Example

struct Box {
    var width: Int
    var height: Int
    func area() -> Int {
        return width * height
    }
    mutating func grow() {
        width += 1
    }
}
var box = Box(width: 3, height: 4)
print(box.area())
box.grow()
print(box.width)
print(box.area())

Key points

  • A struct groups named values called properties into one value.
  • The memberwise initializer takes one value for each property, in the order the properties are written.
  • A property is read by writing the value name, a dot, and the property name.
  • A struct value made with var lets its properties change after it is made.
  • A method is a function placed inside a struct.
  • A mutating method can change a property of its own value.
  • Copying a struct value makes a separate copy.

In this example, the Box struct holds a width and a height, and the area method multiplies them. The first print shows the area 12 for a box that is 3 wide and 4 high. The grow method then raises the width by 1, the next print shows the new width 4, and the last print shows the new area 16.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A Point value is copied into a second variable, and the copy has its x changed to 99. What does the first point print for x if it started at 3?