1.6. More print, String interpolation
Swift allows you to insert values of variables into a String. String interpolation is useful for creating dynamic texts (labels, error messages, debug information, etc.) and formatting texts.
In Swift, String interpolation is done using \(...) notation. Let's look into an example. So far, what we have in our playground are a few variables, such as myNum, myFloat, and multiline. (myNum is a Double, myFloat is a Float, and multiline is a string.)
So let's add the following lines of code to your Playground:
var myString =
"My Double number is \(myNum). My Float number is \(myFloat). And, my multiline string is \(multiline)"
print(myString)If you run the code, the output would be:
My Double number is 12.5. My Float number is 13.0. And, my multiline string is I am a multiline String.
I might look weird, but I am really very simple.
At times I could be very useful!Here, You can see that myNum(a Double), myFloat (a Float), and multiline (even a String) have been interpolated into myString.
Now, If we change the code to the following:
var myString = """
My Double number is \(myNum).
My Float number is \(myFloat).
And, my multiline string is
\(multiline)
"""
print(myString)The output becomes:
Here we see how multiline Strings and String interpolation can be used together to format the texts.
Question:
Can you print the same output by calling the
print()function without creating themyStringvariable?
Last updated
Was this helpful?