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).
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 strings. Here 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.
Here We use 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 18, 2023 (edit).