Start learning free

LESSON 56 OF 415 · STRINGS I

String Concatenation in Swift: + and +=

Lesson Read the full explanation

Remember that string concatenation is used to dynamically generate messages that can be different depending on context.

We most often use it with variables, let's check an example:

let adjective = "awesome"
var message = "AlgoCademy is "

// String concatenation & assignment:
message = message + adjective

print(message) // Output: AlgoCademy is awesome

We first concatenate message and adjective and then we assign the result to message.


Concatenating with +=

Since this is such a common pattern, there is the += operator which does both the concatenation and assignment in one step.

let adjective = "awesome"
var message = "AlgoCademy is "

// With += operator:
message += adjective

print(message) // Output: AlgoCademy is awesome

Concatenating multiple strings:

We can append as many strings as we want using the += operator:

let name = "Andy"
let pet = "dog"
var message = "Hey, "

message += name
message += "! Nice "
message += pet
message += "!"

print(message) // Output: Hey, Andy! Nice dog!


Assignment
Follow the Coding Tutorial and let's practice with string concatenation!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    SWIFT · STRINGS I

    String Concatenation Ii in Swift, explained

    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. With let message = "a", the line message += adjective fails: 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 line message += n is an error: cannot convert value of type 'Int' to expected argument type 'String'. Convert first with message += 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" gives Hey,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:

    1. Append the adjective. message += adjective turns the message into Coding is worthwhile.
    2. Append the ending. message += ", isn't it?" adds the literal text. The apostrophe needs no escape inside double quotes.
    3. 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 = adjective throws the old text away.
    • Typing the word instead of the variable. The exercise gives you adjective to 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.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free