struct Basics / Memberwise Initializer
The Swift struct (structure) is a value type. It can have properties and methods, and unlike a class, it is passed by copy.
Syntax
struct StructName {
// Stored properties
var property1: Type
let property2: Type
// Custom initializer (auto-generated if omitted)
init(property1: Type, property2: Type) {
self.property1 = property1
self.property2 = property2
}
// Method (use mutating to modify properties)
mutating func methodName() {
property1 = newValue
}
}
Syntax reference
| Syntax | Description |
|---|---|
| struct Name { ... } | Defines a structure. |
| memberwise initializer | An initializer matching each stored property is generated automatically. |
| mutating func | Required for methods that modify the structure's properties. |
| Value type (copy semantics) | A copy is created on assignment or when passed as an argument. |
| static var / func | Defines properties and methods that belong to the type itself, not to an instance. |
Sample code
// Define a struct
struct Point {
var x: Double
var y: Double
// Method that calculates the distance to another point
func distance(to other: Point) -> Double {
let dx = x - other.x
let dy = y - other.y
return (dx * dx + dy * dy).squareRoot()
}
// Mutating method that modifies properties
mutating func move(dx: Double, dy: Double) {
x += dx
y += dy
}
// Computed description property
var description: String {
return "(\(x), \(y))"
}
}
// Using the memberwise initializer (no custom init defined)
var p1 = Point(x: 0.0, y: 0.0)
let p2 = Point(x: 3.0, y: 4.0)
print("p1: \(p1.description)")
print("p2: \(p2.description)")
print("Distance: \(p1.distance(to: p2))")
// Value type: copy semantics
var p3 = p1 // A copy is made
p3.move(dx: 1.0, dy: 1.0)
print("p1 (unchanged): \(p1.description)")
print("p3 (after move): \(p3.description)")
// A struct declared with let cannot have its properties modified
let fixedPoint = Point(x: 5.0, y: 5.0)
// fixedPoint.move(dx: 1, dy: 1) // Error: cannot mutate a let constant
Overview
A Swift struct is a value type, so a copy is created whenever you assign it to a variable or pass it to a function. This makes it easier to avoid bugs caused by unintended shared state.
If you do not define a custom initializer, Swift automatically generates a memberwise initializer that accepts all stored properties as arguments. An instance declared with let makes all of its properties immutable — you cannot call mutating methods on it either.
For reference types, see class basics / init() / deinit().
If you find any errors or copyright issues, please contact us.