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
 
    
    - 85
- 6
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.
 
    
    - 234
- 1
- 9
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.
 
    
    - 274,689
- 30
- 353
- 361
- 
                    1@DávidPásztor The pointer is declared as *Unsafe**Mutable**Pointer* – vadian Nov 14 '17 at 11:16
- 
                    my bad, I thought you meant the declaration to be mutable/immutable, not the type of the pointer itself. – Dávid Pásztor Nov 14 '17 at 11:28
- 
                    `struct UnsafeMutablePointer` is a struct. – Martin R Nov 15 '17 at 09:03
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.
 
    
    - 51,403
- 9
- 85
- 116
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
 
    
    - 529,903
- 94
- 1,240
- 1,382