Output: a combination of strings
Let’s declare 2 different variables as strings and give them a text value. So let’s take for example the name John Smith
var name : String = “John”
var surname : String = “Smith”
/* recall that you can also declare the variable without specifying the type, such as var surname = “Smith” */
Now if we want the output to show ” John Smith”, we need to put the 2 variables together. Two strings are put together using the sign “+” or “+=” when using the function print().
print (name + ” ” + surname) // the output is John Smith
/* note that between the 2 variables i have added a ” “, this so to create the space between John and Smith. Without it, the output would be JohnSmith */
Another possibility is to have a pre-determined output and change only a part of the sentence, like for example a Welcome “name”! output. To do so, we will write our static part of the sentence in the print function surrounded by commas and we add the variable part. When we add the variable, we need to insert it between parenthesis and add a “\” before it, as shown here below
print (“Welcome \(name) !”) // the output is Welcome John!
Before moving forward, I would like to present you a special case that we all encounter sooner or later, and this is when we have special characters when we would like to output a sentence. The list includes the following:
- Creating a double quote (“)
- Creating a simple quote (‘)
To do so, we need to add \ in front of the quote. So for example the output of a quote would be:
print(” \” Be the change that you wish to see in the world. \” – Gandhi”)
// the output is “Be the change that you wish to see in the world.” – Gandhi