Problem Statement
Provide a code example in Swift that demonstrates the difference between value semantics (struct) and reference semantics (class). Then explain the implications of using one versus the other in multi-threaded or shared-state scenarios.
Explanation
Consider the code: `struct Point { var x: Int; var y: Int } var p1 = Point(x:0, y:0); var p2 = p1; p2.x = 10; // p1.x still 0` and `class Node { var value: Int; init(_ value:Int) { self.value = value } } var n1 = Node(5); var n2 = n1; n2.value = 10; // n1.value now 10` /n/n This example shows that struct assignment creates an independent copy, class assignment shares a reference. In multi-threaded or shared state use‐cases, value semantics help avoid unintended side-effects and race conditions because each thread works on its own copy; reference types need careful synchronization when shared. Choosing correctly affects thread safety, performance and design clarity.
Practice Sets
This question appears in the following practice sets: