0

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?

3
  • What are you trying to do? Commented Aug 22, 2022 at 13:51
  • Does this answer your question? Pointers in Swift Commented Aug 22, 2022 at 13:53
  • 1
    You have a reference to OtherClass in otherClass and can access referenceVariable that way. Commented Aug 22, 2022 at 14:03

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.