Structs Basics
A struct is a blueprint for creating your own custom kind of value, bundling related pieces of data together under one name.
In this page:
Defining and Using a Struct
A struct declares a new type with named properties, and Swift automatically generates a memberwise initializer that takes all properties as arguments.
Example: Defining and Using a Struct
struct Point {
var x: Int
var y: Int
}
let origin = Point(x: 0, y: 0)
print("Point at (\(origin.x), \(origin.y))")
Login to try C/C++/Java/PHP code in the editor
Structs Are Value Types
When a struct instance is assigned to a new variable or passed to a function, its data is copied, so changes to the copy do not affect the original.
Example: Structs Are Value Types
struct Point {
var x: Int
var y: Int
}
var pointA = Point(x: 1, y: 1)
var pointB = pointA
pointB.x = 99
print("A: \(pointA.x), B: \(pointB.x)")
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting a struct's stored properties must all be given values (or defaults) before the initializer finishes.
- Trying to modify a
letstruct instance's property; the entire instance is immutable when declared withlet. - Assuming structs behave like classes with shared references; structs are value types and are copied on assignment.
Chapter Summary
- A
structbundles related properties and methods into a single custom type. - Structs get an automatic memberwise initializer if you don't write your own.
- Structs are value types: assigning one to a new variable copies its data.
- A
letstruct instance is fully immutable, including all its properties.
🔒
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: