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

How does the variables five & ten get assigned the swap?

In the example earlier in the video, how does the two variables five and ten actually get assigned the new swapped values when the func doesn't return anything and the five and ten aren't called / used in within the function block?

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

var five = 5
var ten = 10

switcheroo(  &five, &ten )

//At this point five is 10, and ten is 5

Thanks for the help! :)

1 Answer

Hey Alan Guilfoyle,

Normally, when you pass value types into a function they are copied by value. This means you are not passing in those five and ten variables directly but rather copying the values from them for use in the functions body.

In this scenario, however, you have the function parameters marked as inout. This means that the changes to these parameters will persist outside the scope of the function. The reason behind this is because when you specify a parameter as inout, it is no longer being passed in as a copy of the value. Instead, what is being passed in is a reference to that specific object in memory. This is why when calling a function that is marked with inout parameters, you need to label the arguments with the & prefix. This lets the compiler know that you are not copying the value here, but rather passing in an actual reference to the object in memory.

Therefore, when you perform these switching operations in the functions body, the changes persist outside the scope of the function.

Good Luck

Thanks for your detailed and thorough answer. That makes sense and I had completely forgotten about pass by reference and pass by value. Thanks again!