为何修改结构体Person的name属性会导致其内存地址变更?
Great question! This behavior boils down to two key Swift concepts: value type semantics and how the withUnsafePointer(to:_:) function works under the hood.
1. withUnsafePointer(to:) uses copies of your struct, not the original variable
First, let’s clarify how withUnsafePointer(to:_:) operates. This function takes its first argument by value, not by reference. That means every time you call withUnsafePointer(to: person), Swift creates a temporary copy of your Person struct on the stack, then passes a pointer to this temporary copy into the closure.
Since each temporary copy gets allocated in a different spot on the stack (stack memory is reused and allocated dynamically as your code runs), you’ll see different memory addresses each time—even if you never modified person at all! You can test this yourself with a simple tweak:
struct Person { var name = "Alex" } var person = Person() withUnsafePointer(to: person) { print($0) } // Example address: 0x000000016fdff248 withUnsafePointer(to: person) { print($0) } // Different address: 0x000000016fdff208
No property changes, but two different addresses—this proves the function is working with copies.
2. Value types don’t change address on property modification (usually)
Structs are value types, but mutable value types (declared with var) allow in-place modifications of their properties. When you run person.name = "John", Swift doesn’t create a new Person instance or move the existing one to a new memory address—it updates the name property directly in the original variable’s memory.
To see the original variable’s fixed address, use & to pass person as an in-out parameter to withUnsafePointer(to:_:). This gives you a pointer to the actual variable, not a copy:
struct Person { var name = "Alex" } var person = Person() withUnsafePointer(to: &person) { print($0) } // Fixed address: 0x000000016fdff248 person.name = "John" withUnsafePointer(to: &person) { print($0) } // Same address as before!
To sum up:
The different addresses in your original code have nothing to do with modifying the struct’s property—they’re just a side effect of withUnsafePointer(to:) creating a new copy of your struct each time it’s called. If you point to the actual variable (using &), the address stays consistent when modifying properties.
内容的提问来源于stack exchange,提问作者Constantine

