Swift arrays are not classes

Swift arrays are not classes

I have been working with swift for a little over a year now and I was going back and reading the Big Nerd Ranch book and was surprised that I had not encountered this in my projects. var anArray = [2,3,4,5,1,2,1,4,5] func changeArray(mArray: [Int]) { let firstElement = mArray[0] mArray[0] = mArray.last! mArray[mArray.count - 1] = firstElement } changeArray(anArray) Since Swift's arrays are structs the value of anArray remains the same. The reason Swift structures are passed by value not by reference. In order for the above to work as intended it would need to pass a reference of the memory location that anArray is contained in (See below): var anArray = [2,3,4,5,1,2,1,4,5] func changeArray(inout mArray: [Int]) { let firstElement = mArray[0] mArray[0] = mArray.last! mArray[mArray.count - 1] = firstElement } changeArray(&anArray) In the above code we are defining a function which takes a reference of a Foo struct by specifying the "inout" directive. We also have to change where we are calling "changeArray()" to pass in a reference by adding the "&" before the anArray variable. Classes on the other hand are always passed by reference. class Foo { var name = "Pooch" } func changeFooName(foo: Foo) { foo.name = "Kangaroo" } let foo = Foo() print("Foo name is \(foo.name)") changeFooName(foo) print("Foo name is \(foo.name)") The above will change the name of the Foo object to "Kangaroo" since it is implied that we will be passing a reference to the changeFooName() function.