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

string concatenation in swift

In the apple documentation for swift it states that you concatenate 2 strings by using the additions operator e.g. :

  1. let string1 = "hello"
  2. let string2 = " there"
  3. var welcome = string1 + string2 4 // welcome now equals "hello there"

however we use + " " + in-between words in order to ensure that the words are not mushed together as it was demonstrated in the video. My question is, is it necessary to do this + " " + in between words when concatenating as the example provided by apple suggests that by simply using the + sign the strings are concatenated with spaces in between the words.

Thank you Alia

3 Answers

If you look closely, in the examples you provided, there is a space before the 'there':

  1. let string2 = " there"

As you well know, in string literals, space is a character.

Anthony Boutinov
Anthony Boutinov
13,844 Points

I would recommend using

let helloString = "Hello"
let thereString = "there!"
let a = "\(helloString) \(thereString)"

This way it is easier to prevent values from gluing together because when you write your code like this, you will most definitely not forget to place a space or some other divider in there.

And as you will see in later iOS courses, teachers here prefer this way of doing things.

Sathya vegunta
Sathya vegunta
4,061 Points

Hi,

We need to add the spaces as mentioned in the video.I have tried this in Xcode playground

with Spaces added

var str1="hello" var str2="world" var welcome=str1+" "+str2 O/P :hello world

without spaces:

var str1="hello" var str2="world" var welcome=str1+str2 O/P :helloworld