How to use UnsafeMutablePointer in swift 4

DerrickHo328 picture DerrickHo328 · Sep 20, 2017 · Viewed 11.7k times · Source

Objective-c has a concept of a pointer to a pointer. If you dereference the first pointer you can access the original

void makeFive(int *n) {
    *n = 5;
}

int n = 0;
makeFive(&n);
// n is now 5

When this is bridged to Swift 3 it becomes an UnsafeMutablePointer

func makeFive(_ n: UnsafeMutablePointer<Int>) {
    n.memory = 5
}
var n: Int = 0
makeFive(&n)
// n is now 5

However, as of Swift 4, this behavior has changed and the memory property is no longer available.

What would be the swift 4 equivalent of the makeFive(_:) function?

Update Thanks to Hamish, I now know that "memory" was renamed to pointee.

Answer

Vini App picture Vini App · Sep 20, 2017

Please check : https://developer.apple.com/documentation/swift/unsafemutablepointer

func makeFive(_ n: UnsafeMutablePointer<Int>) {
    n.initialize(to: 5)
}
var n: Int = 0
makeFive(&n)
// n is now 5