3

I have this playground example:

import UIKit

var testArray: [[String]] = [["2","2"],["1","1"]]

testArray[0][0] = "3" // Working

func getTestArray() -> [String] {

    return testArray[0]

}

var test = getTestArray()[0] = "4" // Error: Immutable Value

How can i get the reference of testArray to change it

Changing test won't change testArray!

5
  • Swift arrays are value types. Your function returns a value, not a reference to the original array. Commented Feb 13, 2018 at 9:43
  • How can i return the reference then? Commented Feb 13, 2018 at 9:45
  • stackoverflow.com/questions/27364117/… Commented Feb 13, 2018 at 9:49
  • Kind of irrelevant, but why are you (still) in Swift 2? Commented Feb 13, 2018 at 10:13
  • @Sweeper it's for a project that uses an outdated sdk and sadly can't be updated Commented Feb 13, 2018 at 10:14

3 Answers 3

3

getTestArray() returns a value, not a reference. Therefore, the value returned by a function cannot be edited, only variables can be changed. To change the variable, use:

var testVal = getTestArray() // get the value
testVal[0] = "4" // change the value
testArray[0] = testVal // SET the value of the reference `testArray` (change the value)
Sign up to request clarification or add additional context in comments.

3 Comments

With this solution getTestArray() would be useless. You could get testArray directly. But maybe there is no better solution
@JonasSchafft To be honest, why you need such a function?
Difficult to explain. But it would help me in an specific situation.
0

You need to assign value to test and than change it:

var test = getTestArray()
test[0] = "4"

1 Comment

Then i`m not changing testArray
0
var test = getTestArray()
test[0] = "4"
print(test)

4 Comments

Then i`m not changing testArray
I need to change testArray. Not something else. Can i get the reference?
They are not reference types
use classes instead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.