2

I want to store a reference to an array element and modify the array element using the reference.

Example Code:

var myArray : [String] = ["foo"]
var element = myArray.first!
element.append("bar")
print(myArray.first!)

Expected Output:

> foobar

Actual Output:

> foo

My expectation was that first would return a reference to the array element. Instead, Swift returns a copy of the element, meaning the array element doesn't get modified.

Is there a way to store a reference to an array element using Swift arrays?

1
  • 1
    this might help Commented Aug 18, 2017 at 22:50

1 Answer 1

1

Swift's String is a value type, so it returns a copy not a reference, if you want to get a reference you should use NSString not String.

Sign up to request clarification or add additional context in comments.

4 Comments

I used String for the sake of example. In the actual code, I am using a custom class.
@user3225395 I’d suggest making an example that doesn’t use a value type in your question.
I debugged my code, and I realized the bug is due to another piece of code that I overlooked. I'll mark this as answered, since it solves the example I gave.
Although the OP chose an example with a value data type, this does not answer the question "How to store a reference to an array element?"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.