Home
Swift
String append Example
This page was last reviewed on Aug 18, 2023.
Dot Net Perls
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).
String Literal
Characters. This example creates a Character array and an empty string. It then adds those Characters to the string with append().
Tip For complex string mutations, building up a new string based on characters is sometimes easiest.
Here We use a for-in loop to iterate over the three characters in the Character array.
Then We add each character 3 times to the result string. We finally print the string to the console.
print
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 18, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.