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 Object-Oriented Swift 2.0 Complex Data Structures Adding Instance Methods

getFullName Code Challenge - Why is String Interpolation Necessary?

In order for the compiler to accept this code, I had to use string interpolation on the return value. Since I have set the return type to String, I do not see why this should be necessary. Shouldn't I be able to simply concatenate the two values?

ie. return firstName + lastName instead of return "(firstName) (lastName)"

structs.swift
struct Person {
    let firstName: String
    let lastName: String

    func getFullName() -> String {
      return "\(firstName) \(lastName)"
    }
}

3 Answers

I'm going to assume that your talking about the compiler in the code challenge? I'm pretty sure the compiler in the website checks for specific output of the code you insert. You are correct, because the constants are set as type String, you should be able to do firstName + lastName in the return and it would put them together. What is nice about the String Interpolation is the ability to format it without having to put in a but of extra whitespace.

return firstName + lastName JesseAnderson

return "(firstName) (lastName)" Jesse Anderson

Formatting asside, I do think it's just the check the compiler runs in it's test case and verifying specific output. But I don't know 100%.

Technically your right, concatenating two string and returning the result is legal code. However, for readability (which I admit can be subjective), string interpolation makes your code easier to read and it can also be seen as a more convienient way to have your variables expressed as strings. You will also likely to find that string interpolation is generally accepted as best practice or preferred style when writing Swift code.

As for the Treehouse code editor, it is probably being pedantic to get you in the habit of using string interpolation.

Jesse (see above) makes a good point about the ease of formatting strings when using string interpolation. This can become tedious and messy when doing concatenation.