Building messages from parts
Concatenation joins strings end to end. It lets a program build a message from pieces that change with the situation, such as a name or an adjective. In Swift, the + operator joins two strings:
let adjective = "awesome"
var message = "AlgoCademy is "
message = message + adjective
print(message) // AlgoCademy is awesome
This first computes message + adjective, then stores the result back in message. The variable is declared with var because its value changes. The text "AlgoCademy is " ends with a space, which is why the final text has a space before awesome: concatenation adds nothing between the parts.
The += operator
Updating a variable with its own old value is so common that Swift has a shorthand. message += adjective means exactly message = message + adjective:
let adjective = "awesome"
var message = "AlgoCademy is "
message += adjective
print(message) // AlgoCademy is awesome
Appending several pieces
Each += adds one more piece at the end, so a message can grow in steps:
let name = "Andy"
let pet = "dog"
var message = "Hey, "
message += name
message += "! Nice "
message += pet
message += "!"
print(message) // Hey, Andy! Nice dog!
The pieces can be variables or string literals, and you can mix them in any order.
Gotchas in Swift
- The target must be a
var. Withlet message = "a", the linemessage += adjectivefails:left side of mutating operator isn't mutable: 'message' is a 'let' constant. The text you append can be a constant. - Both sides must be strings. Swift doesn't convert numbers for you. With
let n = 5, the linemessage += nis an error:cannot convert value of type 'Int' to expected argument type 'String'. Convert first withmessage += String(n), or use interpolation. - Interpolation is often tidier.
"Count: \(n)"builds the same text as"Count: " + String(n)and handles any type. - Spaces are your job.
"Hey," + "Andy"givesHey,Andy. Put the space inside one of the strings. - Strings are values. Appending to one variable never changes another variable that was copied from it earlier.
Appending in a loop
Because += changes the variable it is applied to, it works well inside a loop that builds a longer string piece by piece:
var line = ""
for word in ["swift", "is", "fun"] {
line += word
line += " "
}
print("[" + line + "]")
This prints [swift is fun ]. Each pass adds the word and a space, so a space is left at the end. The brackets in the output make that trailing space visible.
Joining with spaces
The same ideas work for a full name. Both lines below produce Ada Lovelace, and the second is the form most Swift code uses:
let first = "Ada"
let last = "Lovelace"
print(first + " " + last)
print("\(first) \(last)")
The exercise
The starting code has a var and a let:
var message = "Coding is "
let adjective = "worthwhile"
There are three steps:
- Append the adjective.
message += adjectiveturns the message intoCoding is worthwhile. - Append the ending.
message += ", isn't it?"adds the literal text. The apostrophe needs no escape inside double quotes. - Print the result.
print(message)writes the finished sentence to the console.
The full solution, in order:
var message = "Coding is "
let adjective = "worthwhile"
message += adjective
message += ", isn't it?"
print(message)
It prints Coding is worthwhile, isn't it?.
Common mistakes
- Printing before appending. Statements run in order, so
print(message)must come after both+=lines. - Using
=instead of+=.message = adjectivethrows the old text away. - Typing the word instead of the variable. The exercise gives you
adjectiveto append, not a new string. - Forgetting the leading comma. The ending is
", isn't it?", with the comma attached to it.
Key takeaways
+joins two strings, and+=joins and assigns in one step.- The variable being extended must be declared with
var. - Swift joins only strings with strings, so convert other types first or use interpolation.
