Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Gene Bogdanovich
Gene Bogdanovich
14,618 Points

Why does this code work like this? What happened to the arrays as Value Types?

var arrayOfNumbers = [1, 2, 3]
arrayOfNumbers.reverse()
arrayOfNumbers

In the last line of code arrayOfNumbers has become [3, 2, 1]. But how if arrays are Value Types?

1 Answer

andren
andren
28,558 Points

I think you might be confused about what a reference type is. The reverse method modifies the array it is called on, but that has nothing to do with whether the array is a value or reference type.

Take this code:

var arrayOfNumbers = [1, 2, 3]
var arrayOfNumbers2 = arrayOfNumbers
arrayOfNumbers.reverse()
print("Array 1: \(arrayOfNumbers)")
print("Array 2: \(arrayOfNumbers2)")

What do you think the printed output looks like? Well it looks like this:

Array 1: [3, 2, 1]
Array 2: [1, 2, 3]

The first array is reversed while the second is not. This makes sense as I only called the reverse method on the first array, but it only makes sense because an array is a value type. If it was a reference type then both of them would have been reversed because arrayOfNumbers and arrayOfNumbers2 would just be references to the exact same value in memory.

That is the main difference between value types and reference types. Value types retain their own copy of values while reference types just store a reference to a value. This is of course a bit simplified but should do as a basic explanation.

Gene Bogdanovich
Gene Bogdanovich
14,618 Points

I thought that reverse() method takes the copy of arrayOfNumbers, modifies it and returns the copy. And arrayOfNumbers itself is the same because only the copy has been changed.