String
literalsWe surround a string
literal with double
quotes. In Swift a string
literal can use string
interpolation—a variable can be inserted into it.
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).
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.
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
interpolationWith this syntax we can insert variables (like Ints or other Strings) into a place in a String
. No complex string
operations are needed.
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
String
literals are used in nearly every program. They are used in print statements. We use them to create text output in Swift.