title: Passing variables by reference in Swift
body: <p>I started learning c++ and now I am wondering if I can do some things in Swift as well.</p>
  
  <p>I never actually thought about what happens when we pass a variable as an argument to a function in Swift.</p>
  
  <p>Let's use a variable of type <code>string</code> for examples. </p>
  
  <p>In c++ I can pass an argument to a function either by making a copy of it, or by passing a reference/pointer.</p>
  
  <p><code>void foo(string s)</code> or <code>void foo (string&amp; s)</code>;
  In the 1st case the copy of my original variable will be created, and <em>foo</em> will receive a copy. In the 2nd case, I basically pass an address of the variable in memory without creating a copy.</p>
  
  <p>Now in Swift I know that I can declare an argument to a function to be <strong>inout</strong>, which means I can modify the original object.</p>
  
  <p>1) <code>func foo(s:String)</code>...
  2) <code>func testPassingByReference(s: inout String)</code>...</p>
  
  <p>I made an extension to String to print the address of the object:</p>
  
  <pre><code>extension String {
      func address() -&gt; String {
          return String(format: "%p", self);
      }
  }
  </code></pre>
  
  <p>The result was not that I expected to see.</p>
  
  <pre><code>var str = "Hello world"
  print(str.address()) 
  </code></pre>
  
  <blockquote>
    <p>0x7fd6c9e04ef0</p>
  </blockquote>
  
  <pre><code>func testPassingByValue(s: String) {
      print("he address of s is: \(s.address())")
  }
  func testPassingByReference(s: inout String) {
      print("he address of s is: \(s.address())")
  }
  
  testPassingByValue(s: str)
  </code></pre>
  
  <blockquote>
    <p>0x7fd6c9e05270</p>
  </blockquote>
  
  <pre><code>testPassingByReference(s: &amp;str)
  </code></pre>
  
  <blockquote>
    <p>0x7fd6c9e7caf0</p>
  </blockquote>
  
  <p>I understand why the address is different when we pass an argument by value, but it's not what I expected to see when we pass an argument as an inout parameter.</p>
  
  <p>Apple developer website says that</p>
  
  <blockquote>
    <p><a href="https://developer.apple.com/swift/blog/?id=10" rel="nofollow noreferrer">In Swift, Array, String, and Dictionary are all value types.</a></p>
  </blockquote>
  
  <p><strong>So the question is, is there any way to avoid copying objects that we pass to functions (I can have a pretty big array or a dictionary) or Swift doesn't allow us do such things?</strong></p>