Swift Structs

Model data with a struct, which is copied when assigned.

Swift
struct Point {
    var x: Int
    var y: Int

    func distanceSquared() -> Int {
        return x * x + y * y
    }
}

var point = Point(x: 3, y: 4)
print(point.distanceSquared())
point.x = 6
print(point.distanceSquared())
Output
25
52

Explanation

A struct groups stored properties and methods into a value type. Swift generates a memberwise initializer, so Point(x: 3, y: 4) works without writing one.

Structs are copied on assignment, which makes them predictable: changing one copy never changes another. A struct held in a var can have its properties changed, as with point.x = 6.

Explore the dry run
Guided walkthroughReady
1struct Point {
2 var x: Int
3 var y: Int
4
5 func distanceSquared() -> Int {
6 return x * x + y * y
7 }
8}
9
10var point = Point(x: 3, y: 4)
11print(point.distanceSquared())
12point.x = 6
13print(point.distanceSquared())

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
A value type with two Int properties.—
—
Use the generated initializer.point = (3, 4)
—
9 + 16.point = (3, 4)
25
Change one property in place.point = (6, 4)
25
36 + 16.point = (6, 4)
25
52

Cost and common mistakes

O(1) time and space per call.

  • A struct held in a let constant cannot have its properties changed.
  • Because structs are copied, a copy made earlier does not see later changes.

Try it yourself

Predict the second result if y were set to 0 instead of x to 6.

Reveal answer and reasoning

The second call returns 9 + 0 = 9.

Further reading