← Back to Swift Course | Chapter 8: Structs & Classes | Lesson 1 of 9

Structs Basics

A struct is a blueprint for creating your own custom kind of value, bundling related pieces of data together under one name.

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

markup
struct Point {
    var x: Int
    var y: Int
}
let origin = Point(x: 0, y: 0)
print("Point at (\(origin.x), \(origin.y))")

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

markup
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)")
Common Mistakes
  1. Forgetting a struct's stored properties must all be given values (or defaults) before the initializer finishes.
  2. Trying to modify a let struct instance's property; the entire instance is immutable when declared with let.
  3. Assuming structs behave like classes with shared references; structs are value types and are copied on assignment.
Chapter Summary
  • A struct bundles 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 let struct instance is fully immutable, including all its properties.
🔒

Chapter Quiz — Complete all 9 topics to unlock

0/9 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.