Append
With the Swift append()
method we can add characters or another string
to a string
. We must use var
to have a string
that can be modified.
With the plus operator, we can also append and concatenate strings. But sometimes using append()
is clearer in code (it is obvious we are not adding ints).
This example creates a Character array and an empty string
. It then adds those Characters to the string
with append()
.
string
mutations, building up a new string
based on characters is sometimes easiest.for-in
loop to iterate over the three characters in the Character array.string
. We finally print the string
to the console.let chars: [Character] = ["A", "B", "C"] var result = String() // Loop over all Characters in the array. for char in chars { for _ in 0..<3 { // Append a Character to the string. result.append(char) } } // Write the result String. print(result)AAABBBCCC
Append
stringsHere we append a string
to another existing string
. The end result is printed to the console. Append()
can handle characters or entire strings at once.
var result = "cat" // The append method can append a string. result.append(" and dog") print(result)cat and dog
ReserveCapacity
With this method we can increase the memory used for a string
. Then using append()
on the string
can proceed without resizing the string
—this improves performance.
reserveCapacity
with an argument of 100, which accommodates 100 ASCII characters.// Use reserveCapacity to ensure enough memory. // ... This reduces resizing. var pattern = String() pattern.reserveCapacity(100) // Add characters to string. for _ in 0..<100 { pattern += "a" } // Print first 20 characters of the string. print(pattern[pattern.startIndex..<pattern.index(pattern.startIndex, offsetBy: 20)])aaaaaaaaaaaaaaaaaaaa
With append we change strings to have more characters or strings on their ends. This is useful for building up strings from other data sources.