Start learning free

LESSON 55 OF 349 · STRINGS I

String Concatenation in Swift in Swift

Lesson

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 favoriteAnimal 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

    String Concatenation Ii in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free