String Literal, Interpolation
This page was last reviewed on Aug 23, 2023.
Dot Net Perls
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)
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.
No updates found for this page.
© 2007-2024 Sam Allen.