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 Functions in Swift Adding Power to Functions Function Scope

Manish Giri
Manish Giri
16,266 Points

Are function parameters immutable in Swift?

I was playing around with the code from the function scope video, and I got an errorr with this code -

var testArray: [Int] = [1,2,3,4,5]

func arrayModifier(arr: [Int]) -> [Int] {
    /*
    var firstArr = arr
    firstArr.append(10)
    print("FirstArr = \(firstArr)")
    */

    arr.append(10)

    var secondArr = arr
    return secondArr
}

var resultArr = arrayModifier(arr: testArray)

The commented out part works fine(as in the video), but when I try to append a value to the function parameter arr, it failed. Here's the error -

Playground execution failed: error: Swift-Functions.playground:100:5: error: cannot use mutating member on immutable value: 'arr' is a 'let' constant
    arr.append(10)
    ^~~

Does it mean that you cannot modify function parameters at all in Swift? Or is it only applicable to certain data types. Coming from a Java/JS background, this seems confusing.

Thanks!

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,887 Points

Hi Manish,

Yes, function parameters are immutable in Swift (at least, as of Swift 3).

If you want to create a mutable value scoped to the function then declare a new variable equal to the parameter's value. If you want to a make the input parameter mutable and have the same scope as the input variable (so that changes in the function alter the value that was passed in when calling the function), then you can declare that parameter as inout.

Here is a link to Apple's documentation on inout: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html