String literals. We surround a string literal with double quotes. In Swift a string literal can use string interpolation—a variable can be inserted into it.
Literals, notes. We use the let keyword to declare these strings, as they are constants. To have a string that can be modified, please declare it with the var keyword (not let).
Combine strings. We can use the plus operator to combine two strings. This is also called concatenation. The resulting string is printed to the console.
// Two string literals.
let value = "cat "
let value2 = "and dog"// Combine (concatenate) the two strings.
let value3 = value + value2
print(value3)cat and dog
Append. A string that is declared with the var keyword can be appended to. A variable can be reassigned. Here we append to a string and use print to display it.
Also The append() func can be used to add a character on the end of an existing string.
// This string can be changed.
var value = "one"// Append data to the var string.
value += "...two"
print(value)one...two
String interpolation. With this syntax we can insert variables (like Ints or other Strings) into a place in a String. No complex string operations are needed.
Tip To specify an interpolated variable, use an escaped parenthesis. Then specify the variable name.
let name = "dotnetperls"
let id = 100
// Use string interpolation.// ... Create a string with variable values in it.
let result = "Location: \(name), ID: \(id)"
print(result)Location: dotnetperls, ID: 100
A summary. String literals are used in nearly every program. They are used in print statements. We use them to create text output in Swift.
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.