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 (retired) Types Printing Results

Cody White
Cody White
1,490 Points

Using the + vs the interpretive string. The output is the same, why choose one over the other?

These two lines of code print the same thing: var greeting = "(str) (modernProgrammingLanguage)" var greeting = str + modernProgrammingLanguage

why would you use one over the other?

2 Answers

Jeremy Hayden
Jeremy Hayden
1,740 Points

To see the difference try this code in your playground:

var world = "world"
print ("hello \(world)")
print ("hello " + world)

Now change the value of world to 1.

var world = 1
print ("hello \(world)")
print ("hello " + world)

You will get errors on "hello " + world, but not on "hello (world)"

You can't + or concatenate a string with a integer. Now if you are sure that world will only be a string, then your + world will work. But if there is any possibility that you want world to be a different data type, it is safer to use string interpolation.

Andres Oliva
Andres Oliva
7,810 Points

For example, suppose:

let pizza = "pizza"
let sleeping = "sleeping"
let programming = "programming"

it is easier to write:

let str = "My favorite things are \(pizza), \(sleeping) and \(programming)."

than

let str = "My favorite things are" + pizza +", " + sleeping + " and " + programming + "."

It is also much less confusing.

Cody White
Cody White
1,490 Points

Thanks for the quick answer and you're right, much easier to read.