Consider the following Swift code where two variables share a reference to the same class instance. What will be printed?
class Counter { var count = 0 } let a = Counter() let b = a b.count += 1 print(a.count)
Remember that classes in Swift are reference types, so variables can point to the same instance.
Both a and b refer to the same Counter instance. Increasing b.count changes the shared object, so a.count is also 1.
Given the following Swift code using a struct, what will be printed?
struct Point { var x: Int var y: Int } var p1 = Point(x: 5, y: 5) var p2 = p1 p2.x = 10 print(p1.x)
Structs in Swift are value types. Changing a copy does not affect the original.
p2 is a copy of p1. Changing p2.x does not change p1.x, so it remains 5.
Examine the code below. Why does modifying dictB also change dictA?
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)
Think about how classes and dictionaries behave in Swift regarding references.
Dictionaries are value types and copied on assignment, but the values inside are references to the same Wrapper instance. So changing the instance via dictB affects dictA.
Which of the following Swift code snippets will cause a compile-time error?
Consider mutability rules for constants and variables in Swift.
a is declared with let, making it immutable. Trying to append to it causes a compile-time error.
Consider the following Swift code. How many unique Node instances exist after execution?
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
Count how many distinct Node objects are created with Node(...).
Three Node instances are created: n1, n2, and n4. n3 is a reference to n1, not a new instance.