Junior — Middle
In what cases can a value type variable behave like a reference to an object?
sobes.tech AI
Answer from AI
In Swift, value type variables (struct, enum, tuple) are usually copied when assigned or passed to a function. However, if a structure contains reference-type properties (e.g., classes), these properties behave as references, even if the structure itself is a value type.
Example:
class ReferenceType {
var value: Int
init(value: Int) { self.value = value }
}
struct ValueType {
var ref: ReferenceType
}
var a = ValueType(ref: ReferenceType(value: 10))
var b = a
b.ref.value = 20
print(a.ref.value) // Will output 20, because ref is a reference to an object
Thus, a value type variable can behave like a reference if it contains reference types internally. In this case, the structure itself is copied, but the internal objects remain shared.