-2

I want to pass the value as reference.

var a = "*"
var b = ""

func hello(c: inout String){
    b = c
    a = "**"
    print(b)
    print(c)
}

hello(c: &a)

The output for the above is

B: *

C: **

I want to change the value of B as well as in, I want to pass the reference to B not the value

I want the output to be

B: **

C: **

Any help would be appreciated. Thanks in advance

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Parth Soni
  • 67
  • 1
  • 6
  • 1
    Mutating `a` inside the function is already undefined behaviour, and your code crashes with `Simultaneous accesses to 0x1003b92b0, but modification requires exclusive access.` – Martin R May 21 '18 at 11:59
  • Related: [Is Swift pass-by-value or pass-by-reference](https://stackoverflow.com/questions/27364117/is-swift-pass-by-value-or-pass-by-reference). You should also read the [Classes and Structures](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html) chapter of the Swift book, it will help you understand value- and reference types in Swift. – Dávid Pásztor May 21 '18 at 12:06
  • My variable A is in another class and B is in another class, Now if I change value of A from another class then it should be updated here – Parth Soni May 21 '18 at 12:14

1 Answers1

0

Something that you can do is this

var b = ""
var a = "*"{
    didSet{
        b = a
    }
}

and when the value of a changes the b will have the value of a

Vasilis D.
  • 1,416
  • 13
  • 21