In Swift, structs are value types. What does this mean when you assign a struct to a new variable?
Think about how value types behave compared to reference types.
Structs in Swift are value types, so assigning them copies their data. This means changes to one copy do not affect the other.
What is the output of this Swift code?
struct Point { var x: Int var y: Int } var p1 = Point(x: 5, y: 10) var p2 = p1 p2.x = 20 print(p1.x, p2.x)
Remember structs are copied when assigned.
Changing p2.x does not affect p1.x because p2 is a copy of p1.
Consider this Swift code using structs in a multi-threaded environment. What advantage do structs provide here?
struct Counter { var count: Int = 0 mutating func increment() { count += 1 } } var c1 = Counter() var c2 = c1 c2.increment() print(c1.count, c2.count)
Think about how copying data helps when multiple threads work.
Because structs are copied, each thread works on its own copy, avoiding conflicts.
Why do Swift developers often prefer structs over classes for simple data models?
Consider how memory is managed differently for value and reference types.
Structs are value types and do not use reference counting, so they have less overhead than classes.
Which scenario best explains when to choose a struct instead of a class in Swift?
Think about the benefits of value types and copying behavior.
Structs are best when you want simple, immutable, thread-safe data that copies on assignment, unlike classes which share references.