Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS

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.