Swift Classes/Objects

Swift Classes/Objects

Define reference types with stored properties and methods.

Instances share identity and are passed by reference.


Define a Class

Create a class with stored properties and methods, then instantiate and call methods on the instance.

Example

class Counter {
  var value = 0
  func inc() { value += 1 }
}

let c = Counter(); c.inc()


BankAccount

Use an initializer to set up state and instance methods to mutate it.

Example

class BankAccount {
  var balance: Int
  init(balance: Int) { self.balance = balance }
  func deposit(_ amount: Int) { balance += amount }
}

let acc = BankAccount(balance: 100)
acc.deposit(25)
print(acc.balance) // 125

Comments

Leave a Reply

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