Swift Classes
A class is, like a struct, a blueprint that bundles properties and methods. The big difference is that classes are reference types: a variable does not hold the object itself, only a reference to it. Several variables can point at the same object. Classes also support inheritance and deinitializers, which structs do not.
Defining a class and creating objects
Unlike structs, classes get no memberwise initializer. Every stored property must either have a default value or be set in an init you write yourself.
class BankAccount {
let owner: String
var balance: Double
init(owner: String, balance: Double = 0) {
self.owner = owner // self.owner is the property, owner is the parameter
self.balance = balance
}
func deposit(_ amount: Double) {
balance += amount // no `mutating` needed in a class
}
func summary() -> String {
"\(owner): $\(balance)"
}
}
let account = BankAccount(owner: "Hana", balance: 100)
account.deposit(25.5)
print(account.summary())Hana: $125.5
Two things to notice:
accountis aletconstant, yet we changedbalance. For a class,letonly fixes which object the constant refers to — the object'svarproperties can still change.- Methods modify properties without the
mutatingkeyword.
Objects are shared, not copied
Assigning a class instance to another variable copies the reference. Both names now lead to the same object:
class Playlist {
var songs: [String] = []
}
let morning = Playlist()
let shared = morning // same object, two names
shared.songs.append("Sunrise")
morning.songs.append("Coffee Time")
print(morning.songs)
print(shared.songs)
print(morning === shared) // identity check["Sunrise", "Coffee Time"]
["Sunrise", "Coffee Time"]
true
The identity operators === and !== ask "are these the very same object?". That question does not exist for structs, because every struct value is independent.
Identity vs equality
== compares values and only works if the type adopts Equatable; === compares references. Two different objects can be equal without being identical:
class Tag: Equatable {
let name: String
init(name: String) { self.name = name }
static func == (lhs: Tag, rhs: Tag) -> Bool {
lhs.name == rhs.name
}
}
let a = Tag(name: "swift")
let b = Tag(name: "swift")
let c = a
print("a == b :", a == b) // same contents
print("a === b:", a === b) // different objects
print("a === c:", a === c) // same objecta == b : true
a === b: false
a === c: true
Deinitializers
A class can define deinit, which runs automatically just before an object is destroyed. Swift destroys an object when the last reference to it disappears (you will learn the details in Memory Management & ARC).
class TempFile {
let name: String
init(name: String) {
self.name = name
print("Created \(name)")
}
deinit {
print("Deleted \(name)")
}
}
var file: TempFile? = TempFile(name: "draft.txt")
print("Working…")
file = nil // last reference gone → deinit runs
print("Done")Created draft.txt
Working…
Deleted draft.txt
Done
Struct or class?
struct |
class |
|
|---|---|---|
| Kind | Value type (copied) | Reference type (shared) |
| Memberwise initializer | Yes | No — write init yourself |
| Inheritance | No | Yes |
deinit |
No | Yes |
| Changing properties in methods | Needs mutating |
Allowed |
let instance |
Fully frozen | Reference fixed, var properties still changeable |
Identity (===) |
No | Yes |
Tip: Use a class when something has a single identity that many parts of the program should share — a network session, a game character manager, a document open in an editor. Use a struct for plain data.
Note: You can mark a class
final(final class Logger { … }) to forbid subclassing. It documents your intent and lets the compiler optimise method calls.
Test yourself
Which operator checks whether two variables refer to the same class instance?
=====~=is
let acc = BankAccount(...) — can you change acc.balance (declared var)?
- No,
letfreezes everything - Yes,
letonly fixes which objectaccrefers to - Only inside
init - Only if the class is
final
What do classes NOT get automatically that structs do?
- Methods
- A memberwise initializer
- Properties
- The ability to conform to protocols