lancylot2004
lancylot2004

Reputation: 307

Swift Pass Variable to Reference

In C++ you can do

int x = 5;
int &y = x;

So both x and y point to the same place. Can I do this in Swift?

I'm programming a class with some functionality, and another class which is basically a driver.

class Driver {

    var otherClass: OtherClass
    var referenceVariable: Int = otherClass.referenceVariable // how to make a reference here
   
    ...

}

Or is there a better / more semantically correct way to do this in Swift?

Upvotes: 0

Views: 107

Answers (2)

vacawama
vacawama

Reputation: 154543

You could use a computed property for this functionality:

class Driver {

    var otherClass: OtherClass
    var referenceVariable: Int {
        get { otherClass.referenceVariable }
        set { otherClass.referenceVariable = newValue }
    }
   
    ...

}

A computed property doesn't store a value itself. It provides closures for reading and writing the property. In this case, we're operating on the value stored in the otherClass.

Upvotes: 1

Tony Macaren
Tony Macaren

Reputation: 457

Int is a struct in Swift. Structs in Swift are first citizen. Basically structs are value types. Values types usually are copied on assigning.

If you want to use reference type, just use classes.

One of the basic solution for your task is to wrap Int value in a class

final class IntWrapper {

   let value: Int

   init(value: Int) {
      self.value = value  
   }
}

Now, changing referenceVariable: IntWrapper will change all references to it

class Driver {

   var otherClass: OtherClass
   var referenceVariable: IntWrapper = otherClass.referenceVariable // how to make a reference here

  ...
}

If you want to get pointer on your class IntWrapper you can create it this way.

var pointer = UnsafePointer(&i)

But, I suppose, you aren't gonna need it

Upvotes: 0

Related Questions