Why a struct declared by let can be changed?

Viewed 152

In the following code, 'ptr' is a struct declared by let, but its member variable 'pointee' could be changed, Why?
let ptr = UnsafeMutablePointer<Int>.allocate(capacity:1) ptr.pointee = 1

4 Answers

Here, ptr is constant, so you cannot assign a new UnsafeMutablePointer to it, but the structure it holds within can be modified. In short, you cannot reassign anything to a let entity, but you can access and modify its properties.

A pointer is not a struct.

It's a reference type unlike a struct which is value type.

Since you declare the pointer as mutable you can change the pointee (the contents of the memory) but you cannot change the reference itself.

In case of a Pointer, you cannot change the memory address it is pointing to, but you can change the data stored at that memory address. The Pointer is only storing a reference to a memory address, so as long as that address is constant, the Pointer didn't change its value.

UnsafeMutablePointer is a struct, but it declares

public struct UnsafeMutablePointer<Pointee> : Strideable, Hashable {

    public var pointee: Pointee { get nonmutating set }
    public subscript(i: Int) -> Pointee { get nonmutating set }

}

Here "nonmutating set" means that setting the property does not mutate the state of the pointer variable itself.

Therefore ptr.pointee can be assigned a new value even if ptr is a constant, and the same is true for the subscript setter:

let ptr = UnsafeMutablePointer<Int>.allocate(capacity:1)
ptr.pointee = 1
ptr[0] = 2
Related