Linus G. Linus G. - 7 months ago 7
Swift Question

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.

Answer

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 + "\"" }
Comments