user7024499 user7024499 - 1 month ago 13
Javascript Question

Learning Swift - inout functions - Why do they modify the global variable values?

I'm coming from a Javascript background and I'm looking for some clarity on inout with Swift.

In Javascript, a function's parameter only exists within the scope of that function. So for instance I could do this without a problem.

function greet(name) {
name = "randomDude";
return name
}

greet("Barry");


This works because the parameter name only exists within the scope of the greet function. So I can change the value of name.

However, in Swift, I cannot do this:

func greet(name: String) {
name = "Ardvark"
print(name)
}

greet(name: "Drew")


The solution would be to change it to an 'inout' function, which can only take a variable, i.e.:

func greet(name: inout String) {
name = "Ardvark"
print(name)
}

var name = "Drew"
greet(name: name)


However, when I do this, it actually CHANGES the value of var name. Meaning the inout function doesn't modify only the value of the PARAMETER within the scope of the function, but modifies the global variable.

Is this just something I have to accept? Is there a reason it modifies the global variable? How would you modify only the variable 'name' inside the function greet?

Thanks

Answer

The reason the 2nd block of code (1st Swift example) prevents you from changing the value of name is because in Swift 3, all parameters are constants. In other words they are essentially all declared with let.

Imagine your first Swift example as:

func greet(let name: String) {
   name = "Ardvark"
   print(name)
}

Obviously you don't really put let there but that will help you remember that parameters are immutable. This prevents you from changing the value by mistake. If you want to change it just inside the function, use a new variable:

func greet(name: String) {
   let anotherName = "Ardvark"
   print(anotherName)
}

Using inout changes the parameter by "removing the let" and allowing you to change the original variable used when calling the function.

How would you modify only the variable 'name' inside the function greet?

You don't in Swift 3. The parameter is immutable. Assign it to a new variable inside the function.