How to create a pointer in Swift?

Viewed 2673

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.

4 Answers

There are no C style pointers (Unsafe Pointer) as the question asks however objects are shared by reference and structures are by value:

Swift assign, pass and return a value by reference for reference type and by copy for Value Type

structures are always copied when they are passed around in your code, but classes are passed by reference.

For example

How to have pointers/ references to objects

class Song {
    
    init(title: String, image: String, file: String, volume: Float, queuePlayer: AVQueuePlayer, playerLooper: AVPlayerLooper?) {
        self.title = title
        self.image = image
        ...
    }
    var title: String
    var image: String
    ...
}

var aSong = Song(title: "", image: "", ...)

var arrOfSongReferences: [Song] = [Song]()
arrOfSongReferences.append(aSong)

var ptrToASong: Song = aSong

aSong = nil
// Due to Swift garbage collection ARC (Automatic Reference Counting), we still have references to the original aSong object so it won't be deleted

If data is struct you cannot do this

struct Song {
    var title: String
    var image: String
    ...
}

var aSong: Song = Song(title: "", image: "", ...)
var copyOfASong: Song = aSong

Method

You can also pass by reference into a function

// this would be inside a class, perhaps Player. It doesn't have to be a static btw
static func playSound(_ sound: inout Song, volume: Float = 0.0) {
        if (sound.playerLooper == nil) {
               ...
        }
}

// usage
Player.playSound(sound: &aSong)
Related