class Basics / init() / deinit()
In Swift, a class is a reference type. Unlike structures, multiple variables can reference the same instance. Use init() for initialization and deinit for cleanup before the instance is released.
Syntax
class ClassName {
// Stored property
var property: Type
// Initializer
init(property: Type) {
self.property = property
}
// Deinitializer (called when the instance is released)
deinit {
// Cleanup
}
// Method
func methodName() {
// Implementation
}
}
Syntax Overview
| Syntax | Description |
|---|---|
| class Name { ... } | Defines a class. |
| init() { ... } | Defines an initializer (constructor). |
| deinit { ... } | Defines a deinitializer, called when the instance is released. |
| === / !== | Checks whether two variables refer to the same instance (identity operators). |
| Reference type (shared semantics) | Assignment and argument passing share the same reference rather than copying. |
Sample Code
class BankAccount {
let owner: String
var balance: Double
init(owner: String, balance: Double) {
self.owner = owner
self.balance = balance
print("Created account for \(owner)")
}
deinit {
print("Released account for \(owner)")
}
func deposit(_ amount: Double) {
balance += amount
print("Deposited \(amount) → Balance: \(balance)")
}
func withdraw(_ amount: Double) -> Bool {
if balance >= amount {
balance -= amount
print("Withdrew \(amount) → Balance: \(balance)")
return true
}
print("Insufficient balance")
return false
}
}
// Create an instance
let alice = BankAccount(owner: "Alice", balance: 10000)
alice.deposit(5000)
alice.withdraw(3000)
// Reference type: both variables share the same instance
let sameAccount = alice
sameAccount.deposit(1000)
print("Alice's balance: \(alice.balance)") // Reflects the change — same instance
// Use the identity operator to check if they are the same instance
print("Same instance: \(alice === sameAccount)")
let other = BankAccount(owner: "Bob", balance: 0)
print("Different instance: \(alice !== other)")
Notes
Because a class is a reference type, assigning it to another variable does not create a copy — both variables point to the same instance. This is the key difference from struct, which is a value type.
deinit is called automatically when the instance is removed from memory. Use it for cleanup tasks such as closing files or releasing resources. Classes support inheritance, but structs do not. When inheritance is not needed, preferring struct is idiomatic Swift.
For class inheritance, see Inheritance / override / final / super.
If you find any errors or copyright issues, please contact us.