Swift Structs
Model data with a struct, which is copied when assigned.
On this page
Swift functions.
- Model data with a struct, which is copied when assigned.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
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())25 52
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
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 = 6print(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
| Step / line | What happens | State after step | Output 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 |
Behind the scenes
How Swift processes this code
Swift compiles the program; its top-level statements run in source order.
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.