3

In swift how do I put a pointer into an array?

I have several arrays, in all of them I make reference to a variable and when I change it I need it to update in all the other arrays.

Edit: Basically i have an array

var ExampleArray     : NSMutableArray = [
    0,
    "TestString",
    ["*"],
    9,
]

What i want to do is add a pointer to the array so it would be like

var ExampleArray     : NSMutableArray = [
    0,
    "TestString",
    ["*"],
    9,
    //Pointer Here
]

The pointer is to a string that features in many arrays, if update its value in one array i want it to update in all the arrays

How do i declare this?

Thanks

1 Answer 1

1

It literally can't get any simpler than this:

var value: Int = 0
var array: [UnsafeMutablePointer<Int>] = []

withUnsafeMutablePointer(&value, array.append)

But maybe you want to store multiple types, in which case the following should suffice:

var value: Int = 0
var array: [UnsafeMutablePointer<Void>] = []

public func getVoidPointer<T>(inout x: T) -> UnsafeMutablePointer<Void>
{
    return withUnsafeMutablePointer(&x, { UnsafeMutablePointer<Void>($0) })
}

array.append(getVoidPointer(&value))
Sign up to request clarification or add additional context in comments.

3 Comments

This answer is correct enough. It's worth noting though that the this will only accept pointers to Int (obviously). If we use UnsafeMutablePointer<Void>, we can accept pointers to any type. +1 though.
@nhgrif: Well noted. I've updated my answer to reflect your observations.
I've updated my question, i know its really obvious and I'm certainly over thinking it

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.