Swift Language Strings and Characters Concatenate strings


Concatenate strings with the + operator to produce a new string:

let name = "John"
let surname = "Appleseed"
let fullName = name + " " + surname  // fullName is "John Appleseed"

Append to a mutable string using the += compound assignment operator, or using a method:

let str2 = "there"
var instruction = "look over"
instruction += " " + str2  // instruction is now "look over there"

var instruction = "look over"
instruction.append(" " + str2)  // instruction is now "look over there"

Append a single character to a mutable String:

var greeting: String = "Hello"
let exclamationMark: Character = "!"
// produces a modified String (greeting) = "Hello!"

Append multiple characters to a mutable String

var alphabet:String = "my ABCs: "
alphabet.append(contentsOf: (0x61...0x7A).map(UnicodeScalar.init)
                                         .map(Character.init) )
// produces a modified string (alphabet) = "my ABCs: abcdefghijklmnopqrstuvwxyz"

appendContentsOf(_:) has been renamed to append(_:).

Join a sequence of strings to form a new string using joinWithSeparator(_:):

let words = ["apple", "orange", "banana"]
let str = words.joinWithSeparator(" & ")

print(str)   // "apple & orange & banana"

joinWithSeparator(_:) has been renamed to joined(separator:).

The separator is the empty string by default, so ["a", "b", "c"].joined() == "abc".