Tools
Log in
English

Learn to codeSwift

Swift classes and objects

Based on Swift 6.4

Swift structs vs classes, init, self and optionals with if let, step by step.

In one line

Classes (class) and structures (struct) bundle values and behavior into one type. A struct is a value that gets copied whenever it is passed; a class is a reference, so several names can share one object.

Why you need it

Keep item names in one array and weights in another, and sooner or later one is edited without the other. Every place that checks the weight limit repeats the same code.

Put name and weight in Item, and the item list, limit and packing rule in Suitcase. Another bag is one Suitcase(owner:limit:) line, and changing the rule means editing pack only.

Everyday picture

Think of a paper note and a shared online document. Hand someone the note (a struct) and they get their own copy to scribble on. The online document (a class) is shared by link, so every edit shows up for everyone. An optional is a label that says this box may still be empty.

Example code

main.swift · 49 lines
let trip = Suitcase(owner: "Hana", limit: 7)trip.pack(Item(name: "Camera", kg: 2))trip.pack(Item(name: "Boots", kg: 3))trip.pack(Item(name: "Tent", kg: 4)) let towel = Item(name: "Towel", kg: 1)var bigTowel = towelbigTowel.kg = 2let sameBag = tripsameBag.pack(towel) print(trip.summary())if let last = trip.lastPacked {    print("last: \(last.name), towel kg \(towel.kg)")} struct Item {    let name: String    var kg: Int} final class Suitcase {    let owner: String    let limit: Int    private var items: [Item] = []    var lastPacked: Item?     init(owner: String, limit: Int) {        self.owner = owner        self.limit = limit    }     var weight: Int {        items.reduce(0) { $0 + $1.kg }    }     func pack(_ item: Item) {        guard weight + item.kg <= limit else {            print("\(item.name) is too heavy, skipped")            return        }        items.append(item)        lastPacked = item    }     func summary() -> String {        "\(owner): \(items.count) items, \(weight)/\(limit) kg"    }}

When to use it

  • Small values that mean something by themselves (one item, an amount, a point) as a struct
  • Something several parts must see and change together (a bag, the state of one screen, a connection) as a class
  • A slot that may have no value (the last packed item, a search with no result) as an optional Item?

In Swift it is common to start new types as structs and switch to a class only when you need inheritance or a shared object.

A struct gets a memberwise init, such as Item(name:kg:), without writing one. A class needs its own.

Common mistakes

Forcing an optional open with !

! is your promise that a value is definitely there. If the promise is wrong and the value is nil, the code still compiles but the program stops right there. Use if let or guard let to handle both cases.

Wrong

let bag = Suitcase(owner: "Jun", limit: 5)print(bag.lastPacked!.name)

When you run itFatal error: Unexpectedly found nil while unwrapping an Optional value

Fixed

let bag = Suitcase(owner: "Jun", limit: 5)if let last = bag.lastPacked {    print(last.name)} else {    print("nothing packed yet")}

When you run itnothing packed yet

Changing a field of a struct made with let

A struct is one value as a whole, so a let freezes even its var fields. Use var when the value must change. A class behaves differently: trip.pack(...) works on let trip, because let only means the name never points to another bag.

Wrong

let towel = Item(name: "Towel", kg: 1)towel.kg = 2

What the Swift compiler sayserror: cannot assign to property: 'towel' is a 'let' constant

Fixed

var towel = Item(name: "Towel", kg: 1)towel.kg = 2print(towel.kg)

When you run it2

Leaving a property out of init

Swift requires every stored property to have a value when init finishes. liters has no default and is never set, so the code does not compile. Give the parameter a default (liters: Int = 20) or set a value in the declaration.

Wrong

let box = Cooler(brand: "Polar")print(box.brand) final class Cooler {    let brand: String    let liters: Int     init(brand: String) {        self.brand = brand    }}

What the Swift compiler sayserror: return from initializer without initializing all stored properties

Fixed

let box = Cooler(brand: "Polar")print("\(box.brand) \(box.liters)") final class Cooler {    let brand: String    let liters: Int     init(brand: String, liters: Int = 20) {        self.brand = brand        self.liters = liters    }}

When you run itPolar 20

Check yourself

Question 1

An Item (a struct) is assigned to b, and only b changes. What is a.kg?

let a = Item(name: "Map", kg: 1)var b = ab.kg = 5print(a.kg)

Show the answer

Answer: 1. 1 var b = a makes a copy. Changing b leaves a at its original 1.

Question 2

The bag (a class) is assigned to y, and a hat is packed through y. What does x.summary() print?

let x = Suitcase(owner: "Ari", limit: 10)let y = xy.pack(Item(name: "Hat", kg: 1))print(x.summary())

Show the answer

Answer: 2. Ari: 1 items, 1/10 kg x and y point to the same bag object, so packing through either name fills the same array.

Questions people ask

Should I use a struct or a class?

Start small, self-contained values as structs. Use a class when several parts must share and change one object, or when you need inheritance. When unsure, start with a struct and switch later.

Why do optionals (?) exist?

They put "this may have no value" into the type. A String? is a string or nil, and you must unwrap it with if let or guard let before use, so crashes from nil are caught at compile time.

Can I change a class object declared with let?

Yes. For a class, let means the name never points to another object; var properties inside can still change. For a struct, let freezes every field.