Home How to create a pointer in Swift?
Reply: 3

How to create a pointer in Swift?

Drakalex
1#
Drakalex Published in 2017-09-13 18:45:57Z

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.

Phillip Mills
2#
Phillip Mills Reply to 2017-09-13 19:59:12Z

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

Vini App
3#
Vini App Reply to 2017-09-13 19:11:28Z

Same example as @Phillip. But I used struct. In this example rows[0] won't change:

struct Row {
    var rowNumber = 0
}

var rows = [Row]()

var testRow = Row()
testRow.rowNumber = 1

rows.append(testRow)

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

print(testRow.rowNumber) // prints 1
print(selectedRow.rowNumber) // prints 99
print(rows[0].rowNumber)  // prints 1
nyg
4#
nyg Reply to 2017-09-16 21:01:58Z

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)
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.361612 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO