Chapter 80: Swift Structs

1. What is a Struct? (the clearest possible explanation)

A struct (structure) is a value type that lets you group related data together and usually add behavior (methods) to that data.

In simple words:

A struct is like a custom data bag that you design yourself.

Real-life analogy (the one that clicks for almost everyone):

Think of a visiting card / name card you give someone at a meeting.

That card contains:

  • Your name
  • Your phone number
  • Your company
  • Your email
  • Your designation

You can make thousands of copies of your card and give them to people — each copy is independent.

If someone writes a note on their copy (“call him tomorrow”), your original card doesn’t change.

That is exactly how structs behave in Swift.

  • When you assign a struct to a new variable → you get a full copy (not a reference)
  • Changing one copy does not affect any other copy

This is the opposite of classes (which are reference types).

2. Creating your first struct — every part explained

Swift

3. Creating objects (instances) from the struct

Swift

Key memory fact (you must understand this):

Structs are value types → assigning var b = a → full copy is made → changing b never changes a

(Classes are reference types — both variables point to the same object in memory.)

4. Real-life examples — structs you will actually write every day

Example 1 – Product in shopping cart / e-commerce

Swift

Example 2 – Todo / Task item (very common in productivity apps)

Swift

Example 3 – Location / coordinate (very common in maps & location apps)

Swift

5. Very Common Beginner Mistakes & Correct Habits

Mistake Wrong / Risky code Correct / Better habit Why?
Using var for everything var name: String everywhere Default to let unless you actually reassign let prevents bugs + better safety
Force-unwrapping optionals in struct var city: String = address!.city var city: String? or proper optional handling Crash if address is nil
Making everything public public struct User { … } everywhere Default = internal — use public only when needed Better encapsulation & API control
Forgetting mutating for methods that change self func increaseAge() { age += 1 } mutating func increaseAge() { age += 1 } Compile error if missing mutating
Using class when struct is better class Point { let x: Double; let y: Double } Use struct unless you need reference semantics Struct is safer, faster, thread-safe by default

6. Quick Summary — Struct vs Class (decision you make every day)

Question / Feature Struct (value type) Class (reference type) Most developers choose…
Identity matters (=== checks same instance) No — every copy is independent Yes — two variables can point to same object Struct unless identity matters
Can inherit from another type No Yes (single inheritance) Struct unless you need inheritance
Can be used as key in Dictionary/Set Yes (if Hashable) Yes (but need careful Hashable implementation) Struct almost always
Copy behavior Copied on assignment / pass Reference (pointer) copied Struct safer
Thread safety (mutable shared state) Safer (each copy independent) Can cause data races Struct preferred
Typical use in SwiftUI @State, @ObservedObject (structs) ObservableObject / @StateObject Struct for most data

Modern Swift recommendation (2025–2026):

Default to struct for almost everything Use class only when you need:

  • reference semantics (shared mutable state)
  • inheritance
  • Objective-C interop
  • identity comparison (===)

7. Small Practice — Try these

  1. Create a Person struct with:
    • let name: String
    • var age: Int
    • mutating func haveBirthday()
  2. Create a BankAccount struct like the example above
    • private var balance: Double
    • init(initialDeposit:)
    • mutating func deposit(amount:)
    • mutating func withdraw(amount:) -> Bool
  3. Create a Location struct like the example
    • let latitude: Double, longitude: Double
    • var name: String?
    • computed coordinateString

Paste your code here if you want feedback or want to see more polished versions!

What would you like to explore next?

  • Struct vs Class — detailed comparison & decision guide
  • Mutability inside structs (mutating methods)
  • Struct initializers (default, custom, memberwise)
  • Structs in SwiftUI (@State, value types, performance)
  • Or move to another topic (optionals, arrays, closures, switch…)

Just tell me — we’ll continue in the same clear, detailed, patient style 😊

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *