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.

2
  • 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). Commented Sep 20, 2017 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. Commented Sep 20, 2017 at 19:01

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.