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 [+=](<https://developer.apple.com/reference/swift/1540630>)
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 = "!"
greeting.append(exclamationMark)
// 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(_:)](<http://swiftdoc.org/v3.0/type/String/#func-append_-string>)
.
Join a sequence of strings to form a new string using [joinWithSeparator(_:)](<https://developer.apple.com/library/tvos/documentation/Swift/Reference/Swift_SequenceType_Protocol/index.html#//apple_ref/swift/intfm/SequenceType/s:FesRxs12SequenceTypeWx9Generator7Element_zSSrS_17joinWithSeparatorFSSSS>)
:
let words = ["apple", "orange", "banana"]
let str = words.joinWithSeparator(" & ")
print(str) // "apple & orange & banana"
joinWithSeparator(_:)
has been renamed to [joined(separator:)](<http://swiftdoc.org/v3.0/protocol/Sequence/#func-iterator-element-string-joined_>)
.
The separator
is the empty string by default, so ["a", "b", "c"].joined() == "abc"
.