LinusG.
LinusG.

Reputation: 28902

Quotation Mark Lost in Array

I have multiple strings in an array. They each already contain a quotation mark but I want to add another " to each string's end. This is how I do it:

for var str in coordinates {
    str += "\""
    print(str)
}
print(coordinates[0])

print(str) prints My"String" which is how it should be.
But print(coordinates[0] prints My"String

How come? Is this just how the strings are displayed but the actual string contains the "?
Thanks in advance.

Upvotes: 1

Views: 52

Answers (1)

Eric Aya
Eric Aya

Reputation: 70098

In for var the var is only for the current scope inside the loop.

It's not a reference to the strings in the array, it's a copy (value).

You could mutate the existing strings in the array but the Swifty way of doing this is to create a new one, with map for example:

let result = coordinates.map { str in return str + "\"" }

Short version:

let result = coordinates.map { $0 + "\"" }

Upvotes: 4

Related Questions