0
0
Swiftprogramming~20 mins

Reference sharing and side effects in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Reference Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Swift code with class reference sharing?

Consider the following Swift code where two variables share a reference to the same class instance. What will be printed?

Swift
class Counter {
    var count = 0
}

let a = Counter()
let b = a
b.count += 1
print(a.count)
A0
BRuntime error
CCompilation error
D1
Attempts:
2 left
💡 Hint

Remember that classes in Swift are reference types, so variables can point to the same instance.

Predict Output
intermediate
2:00remaining
What is the output when modifying a struct copy in Swift?

Given the following Swift code using a struct, what will be printed?

Swift
struct Point {
    var x: Int
    var y: Int
}

var p1 = Point(x: 5, y: 5)
var p2 = p1
p2.x = 10
print(p1.x)
A5
B10
CCompilation error
DRuntime error
Attempts:
2 left
💡 Hint

Structs in Swift are value types. Changing a copy does not affect the original.

🔧 Debug
advanced
2:30remaining
Why does this Swift code cause unexpected side effects?

Examine the code below. Why does modifying dictB also change dictA?

Swift
class Wrapper {
    var value: Int
    init(_ value: Int) { self.value = value }
}

var dictA = ["key": Wrapper(10)]
var dictB = dictA

dictB["key"]?.value = 20
print(dictA["key"]?.value ?? 0)
ABecause dictionaries are reference types in Swift
BBecause the code has a syntax error and does not compile
CBecause Wrapper is a class and both dictionaries share references to the same Wrapper instance
DBecause dictB is a shallow copy and modifying it changes dictA keys
Attempts:
2 left
💡 Hint

Think about how classes and dictionaries behave in Swift regarding references.

📝 Syntax
advanced
2:00remaining
Which option causes a compile-time error due to incorrect reference handling?

Which of the following Swift code snippets will cause a compile-time error?

A
let a = [1, 2, 3]
a.append(4)
print(a.count)
B
class MyClass { var x = 0 }
var a = MyClass()
var b = a
b.x = 5
print(a.x)
C
struct MyStruct { var x = 0 }
var a = MyStruct()
var b = a
b.x = 5
print(a.x)
D
var a = [1, 2, 3]
var b = a
b.append(4)
print(a.count)
Attempts:
2 left
💡 Hint

Consider mutability rules for constants and variables in Swift.

🚀 Application
expert
3:00remaining
How many unique instances exist after this Swift code runs?

Consider the following Swift code. How many unique Node instances exist after execution?

Swift
class Node {
    var value: Int
    var next: Node?
    init(_ value: Int) { self.value = value }
}

let n1 = Node(1)
let n2 = Node(2)
n1.next = n2
let n3 = n1
n3.value = 3
let n4 = Node(4)
n3.next = n4
A2
B3
C4
D1
Attempts:
2 left
💡 Hint

Count how many distinct Node objects are created with Node(...).