Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Swift Automatically Clone Arguments?

I have been reading the iBook Apple released on Swift, and I am currently reading about functions. In this chapter they discuss the inout keyword. The led me to wonder: does swift automatically clone arguments when they are passed as parameters into functions? If not, could I create a constant equal to the variable I want to pass into the function and then pass it the constant to avoid mutating the variable if I do not want to? ex (By the way, I know that integers are immutable. I am just using integers to keep it simple.)

var variable: Int = 5
let constant = variable
let returnVale = function(constant)

(Sorry if this is an obvious answer. I have very little programming experience.) Thank you for any help.

like image 876
liam923 Avatar asked Feb 12 '23 07:02

liam923


1 Answers

By default, value type variables are passed to methods and functions not just by value, but as constants by value.

That is, not only can the function not change the value of the variable outside the function, it can't even change the value of the variable INSIDE the function.

In order for a function to modify the value inside the function, the function must declare the parameter as a var parameter. Doing this allows the function to modify the variable inside the function, however this still does not effect the variable outside the function.

Only when inout is specified can a function modified the variable outside the function. In this case, we've passed the variable by reference.

For more reading on this topic, here's a link to the official documentation. If you scroll down about two-thirds of the way, you'll find a section called "Constant and Variable Parameters" and another section right after this called "In-Out Parameters".


You don't have to worry about knowing when a function will or won't modify your variable. It's pretty easy to know. When a function has declared a parameter as an inout parameter, you need to use the "address of" operator in the function call with that parameter.

This is the example function from the documentation:

func swapTwoInts(inout a: Int, inout b: Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

Now, given the following two Ints:

var someInt = 3
var anotherInt = 107

We can not call the above function as such:

swapTwoInts(someInt, anotherInt)

The compiler would complain:

Passing value of type 'Int' to an inout parameter requires explicit '&'

To fix the compiler complaint, we must use the address-of operator:

swapTwoInts(&someInt, &anotherInt)

Now the compiler is happy, and that &, the address-of operator, serves to us as a big red flag that we've passed our variables by reference and the function could modify their values.

like image 185
nhgrif Avatar answered Mar 15 '23 05:03

nhgrif