Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a pointer in Swift?

I'm working with Swift 3.

I would like to have this C syntax :

int myVar;
int *pointer = &myVar;

So modifying pointer or myVar does the same exact same thing. Also I don't know if it makes any difference, but in my case myVar is an array containing elements of a class and pointer is a pointer to one element of this array.

like image 231
Drakalex Avatar asked Mar 09 '23 02:03

Drakalex


2 Answers

The & also exists in Swift but can only be used as part of a parameter list (e.g. init, func, closure).

var i = 5
let ptr = UnsafeMutablePointer(&i)
print(ptr.pointee) // 5

// or
let ptr = UnsafeMutablePointer<Int>.allocate(capacity: 1)
ptr.initialize(to: 5)

// or with a closure
let ptr: UnsafePointer = { $0 }(&i)
like image 152
nyg Avatar answered Mar 16 '23 03:03

nyg


(Assuming I understand what you're asking for....)

Try the following code in a playground. It should print "99" three times.

class Row {
    var rowNumber = 0
}

var rows = [Row]()

let testRow = Row()
testRow.rowNumber = 1

rows.append(testRow)

let selectedRow = rows[0]
selectedRow.rowNumber = 99

print(testRow.rowNumber)
print(selectedRow.rowNumber)
print(rows[0].rowNumber)

By default, there's no copying of objects as part of an assignment statement. If it were a struct, that would be different.


Adding a bit for completeness:

If you want a similar effect with scalar values instead of objects, Swift supplies various types of wrappers.

let intPointer = UnsafeMutablePointer<Int>.allocate(capacity: 8)  // Should be 1, not 8 according to comment re: docs
let other = intPointer
other.pointee = 34

print(intPointer.pointee)

(Warning: I haven't used these wrappers for anything except experimenting in a playground. Don't trust it without doing some research.)

like image 24
Phillip Mills Avatar answered Mar 16 '23 03:03

Phillip Mills