Bird
Raised Fist0
Swiftprogramming~20 mins

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

Choose your learning style10 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(...).

Practice

(1/5)
1. In Swift, what happens when you assign one class instance to another variable?
easy
A. The compiler throws an error because classes cannot be assigned.
B. A new copy of the object is created; changes do not affect each other.
C. Both variables refer to the same object; changes affect both.
D. The original object is deleted and replaced by the new variable.

Solution

  1. Step 1: Understand class assignment behavior

    In Swift, classes are reference types, so assigning one instance to another variable makes both variables point to the same object.
  2. Step 2: Effect of modifying through one variable

    Changing the object through one variable affects the object seen by the other variable because they share the same reference.
  3. Final Answer:

    Both variables refer to the same object; changes affect both. -> Option C
  4. Quick Check:

    Class assignment shares references = D [OK]
Hint: Classes share references; variables point to the same object [OK]
Common Mistakes:
  • Thinking classes copy data on assignment
  • Confusing classes with structs
  • Assuming changes affect only one variable
2. Which of the following is the correct way to declare a class instance and assign it to another variable in Swift?
easy
A. let obj1 = MyClass(); let obj2 = obj1
B. var obj1 = MyClass() var obj2 = obj1
C. let obj1 = MyClass() let obj2: MyClass = obj1()
D. var obj1 = MyClass() let obj2 = new MyClass()

Solution

  1. Step 1: Check correct syntax for class instance creation

    In Swift, you create a class instance with MyClass() and assign it to a variable using let or var with an equals sign.
  2. Step 2: Verify assignment to another variable

    Assigning obj1 to obj2 is done simply by let obj2 = obj1; no parentheses or 'new' keyword are used.
  3. Final Answer:

    let obj1 = MyClass(); let obj2 = obj1 -> Option A
  4. Quick Check:

    Correct class instance assignment syntax = A [OK]
Hint: Use let/var with equals and no 'new' keyword in Swift [OK]
Common Mistakes:
  • Using 'new' keyword like other languages
  • Adding parentheses after variable names
  • Missing semicolons but Swift allows them optionally
3. Consider this Swift code:
class Box {
  var value: Int
  init(value: Int) { self.value = value }
}

let box1 = Box(value: 10)
let box2 = box1
box2.value = 20
print(box1.value)

What is the output?
medium
A. 20
B. 10
C. Compilation error
D. Runtime error

Solution

  1. Step 1: Understand reference sharing in class instances

    box1 and box2 both refer to the same Box object because classes are reference types.
  2. Step 2: Effect of changing box2.value

    Changing box2.value to 20 changes the single shared object, so box1.value also reflects 20.
  3. Final Answer:

    20 -> Option A
  4. Quick Check:

    Class reference sharing means box1.value = 20 [OK]
Hint: Changing one reference changes all pointing to same object [OK]
Common Mistakes:
  • Assuming box1.value stays 10 after box2 changes it
  • Confusing class with struct behavior
  • Expecting a compile or runtime error
4. What is wrong with this Swift code snippet?
class Person {
  var name: String
  init(name: String) { self.name = name }
}

var p1 = Person(name: "Alice")
var p2 = p1
p2.name = "Bob"
print(p1.name)
medium
A. p2 should be declared with let, not var.
B. Nothing is wrong; output is "Bob".
C. Changing p2.name does not affect p1.name.
D. Class Person must be a struct to allow copying.

Solution

  1. Step 1: Analyze reference sharing in the code

    p1 and p2 both point to the same Person instance because Person is a class.
  2. Step 2: Effect of changing p2.name

    Changing p2.name to "Bob" changes the shared object, so p1.name also becomes "Bob".
  3. Final Answer:

    Nothing is wrong; output is "Bob". -> Option B
  4. Quick Check:

    Class reference sharing means p1.name = "Bob" [OK]
Hint: Class instances share references; changes reflect everywhere [OK]
Common Mistakes:
  • Expecting p1.name to remain "Alice"
  • Thinking var vs let affects reference sharing
  • Believing class must be struct for copying
5. You want to create a copy of a class instance in Swift so that modifying the copy does not affect the original. Which approach correctly achieves this?
hard
A. Declare the class as a struct instead of a class.
B. Assign the instance to a new variable; this automatically copies it.
C. Use the 'clone' keyword to duplicate the instance.
D. Make the class conform to NSCopying and implement copy(with:), then use copy().

Solution

  1. Step 1: Understand copying behavior of classes

    Classes in Swift do not copy on assignment; variables share references by default.
  2. Step 2: Use NSCopying protocol for explicit copying

    To create a true copy, the class must conform to NSCopying and implement copy(with:) method, then call copy() to get a new instance.
  3. Step 3: Evaluate other options

    Assigning to a new variable shares the reference. Declaring as a struct changes the type but is not always possible. The 'clone' keyword does not exist in Swift.
  4. Final Answer:

    Make the class conform to NSCopying and implement copy(with:), then use copy(). -> Option D
  5. Quick Check:

    Explicit copy via NSCopying = C [OK]
Hint: Use NSCopying protocol to make class copies [OK]
Common Mistakes:
  • Assuming assignment copies the object
  • Confusing structs with classes for copying
  • Expecting a 'clone' keyword in Swift
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard