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 Swift Basics Swift Types Strings

Usage of string concatenation

I would like to ask - is there a case when we should (or even must) use string concatenation? In the video string interpolation was able to do more and even on its Wiki page it says "String interpolation allows easier and more intuitive string formatting and content-specification compared with string concatenation".

2 Answers

andren
andren
28,558 Points

The end result is identical. String concatenation has existed for ages and is relatively standardized between many modern programming languages, so many people use it out of habit.

If you prefer interpolation (I happen to be in the same camp as you) then there is nothing wrong with just using that. Though keep in mind that once you get into the real world and start working on a team project, they might have a coding style guideline that dictates that you only use interpolation or concatenation. This is to ensure the code written by the team is consistent with each other.

Yes, there are times where string concatenation requires less typing. For example, if we just want to stick something to the end of a string, string concatenation takes less typing and sometimes is even easier to read.

let name = "Alex"

"Hello \(name)"

// the above is the same as

"Hello " + name

// however, I'd still say "Hello \(name)" is cleaner. But, in this case:

var name = "" // we're making an empty string
name = "\(name)A"
name = "\(name)l"
name = "\(name)e"
name = "\(name)x"

// the code above is REALLY CONFUSING. However, with string concatenation, it's easier to understand...

name = ""
name = name + "A"
name = name + "l"
name = name + "e"
name = name + "x"

I hope you understand :grin:

:dizzy: ~Alex :dizzy: