Welcome to the Treehouse Community
Looking to learn something new?
Greg Kaleka39,019 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 . The line of code:
return "\(firstName) \(middleName ?? "") \(lastName)"
Anyone see what the problem is? If
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
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)"