Swift inout passed array does not seem to effect original array

114 Views Asked by At

I have a simple case where I must not be using inout correctly.

import Foundation

func test_inout(file_data: inout Array<String>){

          let inString = "abc,def,xyz"
            let file_data = inString.split { $0 == ","}.map(String.init)
            print(file_data)
        }

var array: Array = ["initial string"]
test_inout(file_data: &array)
print(array)

The output is:

["abc", "def", "xyz"]
["initial string"]

The contents of the passed array has changed as seen by the first print but has not changed as seem by the second print. I do have it as a var and used the & in the call.

1

There are 1 best solutions below

0
On BEST ANSWER

You are using inout just fine. The problem is the way you use let. You are creating another file_data that overshadows the inout variable; the inout itself is never touched, so nothing happens to it.

Solution: In this line:

let file_data = inString.split { $0 == ","}.map(String.init)

...delete let.