Display Name
Display Name

Reputation: 1035

How to put reference to variable instead of variable value into an array

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

Upvotes: 3

Views: 141

Answers (1)

Vatsal
Vatsal

Reputation: 18181

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))

Upvotes: 1

Related Questions