Adding to a String in Swift 4

Viewed 17462

I was wondering the best way to add to a String in Swift 4. Did Apple create a better way than stringName.characters.append(“hi”)

Edit: Noted below which I never knew you used to be able to use a String.append(). I was trying to get at the fact that in Swift 4 you don't have to use .characters anymore. I was trying to help out new people to swift 4 by making a question that they might ask so that they can save time by not using .characters after a String variable.

2 Answers

According to Swift 4 Documentation, String values can be added together (or concatenated) with the addition operator (+) to create a new String value:

let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// welcome now equals "hello there"

You can also append a String value to an existing String variable with the addition assignment operator (+=):

var instruction = "look over"
instruction += string2
// instruction now equals "look over there"

You can append a Character value to a String variable with the String type’s append() method:

let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"
Related