← 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.
Syntax
swift
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

markup
// 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))")

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
// 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)")
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
  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.