Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Simen Anthonsen
Simen Anthonsen
1,097 Points

Loop through an array of strings

Does someone know how you can loop through an array of strings, and set each string to an empty string?

In my app have created 3 variables that stores a string each. I have then appended those 3 variables to an array, and tried this method: for string in strings { string = "" } I get an error saying string is a constant. I then change my code to for var string in strings... The error goes away, but it does´t work

1 Answer

Christin Lepson
Christin Lepson
24,269 Points
for index in 0..<strings.count {
    array[index] = ""

When you made the loop for string in strings the 'string' value is actually a copy of the element in the array. When you set string="", you were only changing the value of a copy you had made.

To change the actual value of the element in the array, instead of just making a copy, you have to use strings[indexNumber] = "" instead.