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

iOS

String Concatenation with variable 1 stored in variable 2 not changing with alterations to variable 1.

var myBody = "dead"
var sentence = "I told them my body was \(myBody)!"
myBody = "alive"
sentence

The var sentence then prints out "I told them my body was dead!" instead of "I told them my body was alive!"

You can fix this problem (and clean up your code) by simply placing your redeclaration(s) under the initial assignment of myBody. Like so:

var myBody = "dead"
myBody = "alive"
var sentence = "I told them my body was \(myBody)!"

Remember that order matters. You cannot change the value of myBody in sentence, if sentence has already run. Re-assignment can only happen right after the initial assignment. Hope this helps!

1 Answer

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,863 Points

I'm not sure which course your are referring to, but the code you provided will produce the output it is producing because of the order of the code.

You declare myBody You declare the string sentence You re-declare the variable myBody

You look at sentence.

It doesn't matter that you look at the sentence variable after the re-declaration. The sting assigned to sentence has already been 'produced'. You can change the variable all you want after, but the sentence won't change. If you were to re-declare the sentence string again after the second declaration of the myBody. Then yes, but as it is now... the sentence is 'written' before the change. Make sense?

:dizzy: