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 Intermediate Swift 2 Extensions and Protocols Method Dispatch in a Protocol Extension

Greg Kaleka
Greg Kaleka
39,021 Points

String interpolation bug in this video

Just a quick note about a line of code in this video that introduces a bug. I know it's just an example, and the bug is incredibly minor, but I can't help myself :smile:. The line of code:

return "\(firstName) \(middleName ?? "") \(lastName)"

Anyone see what the problem is? If middleName is nil, we'll end up with firstName  lastName, with two spaces. Here's a fix:

return "\(firstName) \(middleName != nil ? middleName! + " " : "")\(lastName)"

We check to see if middleName isn't equal to nil: if it's not, we add it plus a space, if it is nil, we add an empty string. importantly, we do not include a space between this statement and lastName.

Good catch. Nice fix!

1 Answer

James Estrada
seal-mask
.a{fill-rule:evenodd;}techdegree
James Estrada
Full Stack JavaScript Techdegree Student 25,866 Points

Actually you only need to remove the space in between the last parenthesis of middleName and the beginning of lastName from the original string interpolation, like this:

return "\(firstName) \(middleName ?? "")\(lastName)"
Greg Kaleka
Greg Kaleka
39,021 Points

This works if there's no middle name, but if a middle name does exist, you'll end up with "James AwesomeEstrada".