0
0
Swiftprogramming~20 mins

Classes are reference types in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Class Reference Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of class instance assignment
What is the output of this Swift code?
Swift
class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
}

let person1 = Person(name: "Alice")
let person2 = person1
person2.name = "Bob"
print(person1.name)
A"Alice"
B"Bob"
CCompilation error
D"person1"
Attempts:
2 left
💡 Hint
Remember that classes are reference types, so both variables point to the same instance.
Predict Output
intermediate
2:00remaining
Effect of modifying a class property via one reference
What will be printed by this Swift code?
Swift
class Counter {
    var count = 0
}

let c1 = Counter()
let c2 = c1
c2.count += 5
print(c1.count)
A5
B0
CCompilation error
Dnil
Attempts:
2 left
💡 Hint
Both variables refer to the same instance, so changes via one affect the other.
🔧 Debug
advanced
2:00remaining
Why does this code print 20 instead of 5?
Consider this Swift code. Why does it print 20 instead of 5?
Swift
class Number {
    var value: Int
    init(value: Int) {
        self.value = value
    }
}

func doubleValue(_ num: Number) {
    num.value *= 2
}

let n = Number(value: 5)
doubleValue(n)
doubleValue(n)
print(n.value)
ABecause the function doubles the value once, but the print statement is wrong
BBecause the function doubles the value twice, so 5 * 2 = 10
CBecause classes are reference types, the same instance is modified twice, resulting in 20
DBecause the function doubles the same instance twice, so 5 * 2 * 2 = 20
Attempts:
2 left
💡 Hint
Trace the value changes step by step.
Predict Output
advanced
2:00remaining
Output when copying class instance to a new variable
What is the output of this Swift code?
Swift
class Box {
    var content: String
    init(content: String) {
        self.content = content
    }
}

var box1 = Box(content: "Apple")
var box2 = box1
box2.content = "Orange"
print(box1.content)
A"Orange"
BRuntime error
C"box1"
D"Apple"
Attempts:
2 left
💡 Hint
Remember that assigning a class instance copies the reference, not the object.
Predict Output
expert
3:00remaining
Output of modifying nested class references
What will this Swift code print?
Swift
class Engine {
    var horsepower: Int
    init(horsepower: Int) {
        self.horsepower = horsepower
    }
}

class Car {
    var engine: Engine
    init(engine: Engine) {
        self.engine = engine
    }
}

let engine1 = Engine(horsepower: 150)
let car1 = Car(engine: engine1)
let car2 = car1
car2.engine.horsepower = 200
print(car1.engine.horsepower)
A150
Bnil
CCompilation error
D200
Attempts:
2 left
💡 Hint
Both cars share the same engine instance because classes are reference types.