// 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"
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 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.