Classes Are References
Part of the Object Oriented Programming section of Coddy's Swift journey. Lesson 5 of 57.
A class is a reference type: a variable holds a reference to the object, not a copy of it. Assigning an instance to another variable gives a second name for the same object:
class Wallet {
var coins = 10
}
let mine = Wallet()
let alias = mine
alias.coins = 25
print(mine.coins)Output:
25=== checks whether two references point to the same instance. Two separate instances are different objects even when all their properties match:
class Wallet {
var coins = 10
}
let a = Wallet()
let b = a
let c = Wallet()
print(a === b)
print(a === c)Output:
true
falseA function that receives an instance works on the caller's object, so changes made inside the function stay visible afterwards:
class Wallet {
var coins = 10
}
func payFee(_ wallet: Wallet) {
wallet.coins -= 3
}
let w = Wallet()
payFee(w)
payFee(w)
print(w.coins)Output:
4let fixes the reference, not the object. A constant holding a class instance cannot point to another instance, but the instance's var properties can still change. Arrays of instances hold references too:
class Wallet {
var coins = 10
}
let shared = Wallet()
let team = [shared, shared]
team[0].coins = 99
print(shared.coins)
print(team[1].coins)Output:
99
99Challenge
EasyA team shares one Budget. Complete spend(_:amount:), a function that takes a budget and subtracts the amount only if enough is left, returning true when the spending was allowed. Then complete runTeam(start:purchases:): create one budget, let every purchase spend from that same budget, and return one line per purchase (ok 30 or denied 80) followed by left 20.
The supplied code reads the starting budget and the purchases as a comma-separated line, and prints each returned line.
Your code goes in Budget.swift and Functions.swift. main.swift holds the supplied input/output code and cannot be edited.
Try it yourself
// Supplied input/output code: keep it as it is
var input: [String] = []
while let line = readLine() { input.append(line) }
let purchases = input[1].split(separator: ",").map { Int($0)! }
for line in runTeam(start: Int(input[0])!, purchases: purchases) { print(line) }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesMethods and selfInitializersClasses Are ReferencesRecap - Library Card4Encapsulation
Access ControlRead-Only From OutsideGuarding StateFailable InitializersRecap - Bank Account7Polymorphism and Generics
PolymorphismType CastingGeneric FunctionsGeneric TypesRecap - Shape Calculator5Inheritance
SubclassesOverriding MethodsInitializers and superfinal and HierarchiesRecap - Employee Hierarchy11Project: Library Management
Books and MembersBorrowing BooksPractice on your own: Swift playground