0

Since the structs are value types in Swift, so their memory is ofcourse allocated on the stack.

My question is, why is the memory address not changed when different instances of struct are assigned in the same variable.

Explanation:

For the below struct,

struct Person {
    var name: String

    init(_ name: String) {
        self.name = name
    }
}

if I create the instances of Person like,

var p = Person("John")
withUnsafePointer(to: &p) {
    print("\(p) has address: \($0)") //0x000000010dcea3c0
}
p = Person("Jennifer")
withUnsafePointer(to: &p) {
    print("\(p) has address: \($0)") //0x000000010dcea3c0
}
p = Person("Lisa")
withUnsafePointer(to: &p) {
    print("\(p) has address: \($0)") //0x000000010dcea3c0
}

Why is the same address printed everytime?

1 Answer 1

4

This is because you are using same variable. Take this example

var p (This is allocating memory to hold your value)

and now you are just changing the values and not the variable which is already been allocated to a memory location.

Sign up to request clarification or add additional context in comments.

2 Comments

Then what about the content inside p? That'll have different address right?
@PGDev, within address you can update your content and thats what is happening here. So when you try printing content at this address, it will be updated.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.