Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: How to store a reference to Double, Int

I would like to store a reference to a primitive type (Double, Int) in Swift, so that i one variable is changed, the other one is changed, too. Here is an example:

class MyClass {
    var value: Double?
}

var myValue = 1.0

var instance = MyClass()
instance.value = myValue    // <-- how to set a reference?

myValue = 2.0               // => I want instance.value to change to 2.0
instance.value = 3.0        // => I want myValue to change to 3.0

Is that possible?

like image 598
adamsfamily Avatar asked Dec 07 '25 06:12

adamsfamily


1 Answers

You can use class-holder:

class Ref<T> {
  var value: T

  init(_ value: T) {
    self.value = value
  }
}

Or try to read about In-Out Parameters and maybe it can help you in some way:

In-Out Parameters

Variable parameters, as described above, can only be changed within the function itself. If you want a function to modify a parameter’s value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter instead.

You write an in-out parameter by placing the inout keyword at the start of its parameter definition. An in-out parameter has a value that is passed in to the function, is modified by the function, and is passed back out of the function to replace the original value.

You can only pass a variable as the argument for an in-out parameter. You cannot pass a constant or a literal value as the argument, because constants and literals cannot be modified. You place an ampersand (&) directly before a variable’s name when you pass it as an argument to an inout parameter, to indicate that it can be modified by the function.

func swapTwoInts(inout a: Int, inout _ b: Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
// prints "someInt is now 107, and anotherInt is now 3"
like image 72
Arsen Avatar answered Dec 08 '25 21:12

Arsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!