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:
Syntax
struct TypeName {
var property: Type
let constant: Type
}
var instance = TypeName(property: value, constant: value) // memberwise init
instance.property
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
// Define a struct `Point`
struct Point {
var x: Int
var y: Int
}
// Declare a constant `origin`, set to `Point(x: 0, y: 0)`
let origin = Point(x: 0, y: 0)
// Print "Point at (\(origin.x), \(origin.y))" to the console
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
// Define a struct `Point`
struct Point {
var x: Int
var y: Int
}
// Declare a mutable variable `pointA`, initialized to `Point(x: 1, y: 1)`
var pointA = Point(x: 1, y: 1)
// Declare a mutable variable `pointB`, initialized to `pointA`
var pointB = pointA
pointB.x = 99
// Print "A: \(pointA.x), B: \(pointB.x)" to the console
print("A: \(pointA.x), B: \(pointB.x)")
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
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: