huwr
huwr

Reputation: 1800

How to make new pointer in Swift?

Say I have a var with an Int:

var f = 3

Now I would like to have an UnsafePointer<Int> to that var. If I were passing it to a function I could do it like this:

functionTakesAPointer(&f)

But I need to be able to do something like this:

var g = &f

which is not allowed.

NB: I am aware this is not the 'Swift way'; this is a highly contrived example I invented while fiddling around with Swift.

Upvotes: 1

Views: 65

Answers (1)

Marc Khadpe
Marc Khadpe

Reputation: 2002

You can create a mutable pointer to variable f as follows:

let g = withUnsafeMutablePointer(&f, { $0 })

And here's how you can create an immutable pointer to f.

let g = withUnsafePointer(&f, { $0 })

Upvotes: 2

Related Questions