Member-only story
I Changed One Swift Variable. Why Did Another Value Change?
The interviewer writes this Swift code on the screen:
final class Settings {
var theme = "Light"
}
struct UserProfile {
var name: String
var settings: Settings
}
var first = UserProfile(
name: "Alex",
settings: Settings()
)
var second = first
second.settings.theme = "Dark"
print(first.settings.theme)
print(second.settings.theme)The candidate expects:
Light
DarkBut Swift prints:
Dark
DarkThe interviewer asks one question:
“You changed second. Why did first change too? Isn't UserProfile a struct?”
This is where a simple Swift interview question gets interesting.
friend link
The candidate knows that structures are value types. Assigning one structure to another should give you an independent value, right?
So why did changing one variable affect the other?
The answer reveals an important detail about Swift: a struct can have value semantics while still containing references to shared, mutable objects.










