10

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.

Hamish
  • 78,605
  • 19
  • 187
  • 280
DerrickHo328
  • 4,664
  • 7
  • 29
  • 50
  • 7
    As of *Swift 3*, it's `.pointee`; but don't use `UnsafeMutablePointer` here. Use `inout` if you need to mutate a caller-side variable (and this shouldn't be that often). – Hamish Sep 20 '17 at 18:52
  • Thanks for the correction and rare it certainly is! Otherwise I'd find it in stack overflow. I wasn't aware of the name change. I am mainly using UnsafeMutablePointer for objective-c compatibility since "inout" is a swift only feature. – DerrickHo328 Sep 20 '17 at 19:01

1 Answers1

6

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
Vini App
  • 7,339
  • 2
  • 26
  • 43
  • 11
    Be careful with this; the pointee is *already* initialised, so you shouldn't really be calling `initialize(to:)` on it. It will *happen* to work in this case because the `Pointee` is a trivial type (`Int`), but will produce undefined behaviour for non-trivial pointee types (I think at least; although the best case scenario is still leaking memory). The operation you want here is *assignment* to the pointee; and that's done by setting the `pointee` property of the pointer. – Hamish Sep 20 '17 at 23:04