Search code examples
swiftstructletunsafemutablepointer

Why a struct declared by let can be changed?


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


Solution

  • 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