1

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?

11
  • 2
    Set is a value type. set and pointer.pointee are independent values. Adding an element to the latter does not change the former. Commented Dec 7, 2016 at 14:36
  • 1
    What do you need the reference for? You can "box" a value in a reference type (class), or pass it as inout argument to functions. More context would b e helpful. Commented Dec 7, 2016 at 14:44
  • 2
    There is also 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. Commented Dec 7, 2016 at 14:50
  • 1
    Here is a remotely related question for arrays: stackoverflow.com/questions/28796288/…. Commented Dec 7, 2016 at 14:53
  • 2
    The nested function with an inout parameter is likely the most Swift-like way to do this. There is a reason Swift puts "Unsafe" in those type names; they're discouraged and exist mostly for compatibility with C, not for general use. Commented Dec 7, 2016 at 14:57

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.