Concatenation

You can do much more than create simple strings. Sometimes you need to manipulate a string, and one common way to do so is to combine it with another string.

In Swift, you do this in a rather simple way: by using the addition operator. Just as

you can add numbers, you can add strings:

var message = "Hello" + " my name is " let name = "Matt"

message += name // "Hello my name is Matt"

You need to declare message as a variable rather than a constant because you want to modify it. You can add string literals together, as in the first line, and you can add string variables or constants together, as in the last line.

It’s also possible to add characters to a string. However, Swift’s strictness with types means you have to be explicit when doing so, just as you have to be when you work with numbers if one is an Int and the other is a Double.

To add a character to a string, you do this:

let exclamationMark: Character = "!"

message += String(exclamationMark) // "Hello my name is Matt!"

With this code, you explicitly convert the Character to a String before you add it to

message.

results matching ""

    No results matching ""