I am not able to use UnsafeMutablePointer to refer to a Struct variable in Swift. Look at this playground example:
import Cocoa
var set: Set<Int> = []
let pointer = UnsafeMutablePointer<Set<Int>>.allocate(capacity: 1)
pointer.initialize(to: set)
pointer.pointee.insert(1)
Swift.print(set)
the output is [] while I expected [1]. What am I missing?
BONUS QUESTION: should I explicitly deinitialize the pointer after the usage?
Setis a value type.setandpointer.pointeeare independent values. Adding an element to the latter does not change the former.withUnsafeMutablePointer(to: &set) { ... }which calls the closure with a pointer to the value. But that pointer is only valid inside the closure. Generally Swift allows the creation of pointers to values only in a controlled scope which guarantees the lifetime of the pointed-to value.