Skip to main content

String Interpolation

About 2 minSwiftiOSArticle(s)bloghackingwithswift.comcrashcourseswiftxcodeappstoreios

String Interpolation 관련

Hacking with iOS – learn to code iPhone and iPad apps with free Swift tutorials

Learn Swift coding for iOS with these free tutorials – learn Swift, iOS, and Xcode

String Interpolation | Hacking with iOS

String Interpolation

This is a fancy name for what is actually a very simple thing: combining variables and constants inside a string.

Clear out all the code you just wrote and leave only this:

var name = "Tim McGraw"

If we wanted to print out a message to the user that included their name, string interpolation is what makes that easy: you just write a backslash, then an open parenthesis, then your code, then a close parenthesis, like this:

var name = "Tim McGraw"
"Your name is \(name)"
Adding a name to a String using interpolation.
Adding a name to a String using interpolation.

The results pane will now show "Your name is Tim McGraw" all as one string, because string interpolation combined the two for us.

Now, we could have written that using the + operator, like this:

var name = "Tim McGraw"
"Your name is " + name
Adding a name to a String using the plus operator.
Adding a name to a String using the plus operator.

…but that's not as efficient, particularly if you're combining multiple variables together. In addition, string interpolation in Swift is smart enough to be able to handle a variety of different data types automatically. For example:

var name = "Tim McGraw"
var age = 25
var latitude = 36.166667

"Your name is \(name), your age is \(age), and your latitude is \(latitude)"
Interpolating a String, Int, and Double.
Interpolating a String, Int, and Double.

Doing that using + is much more difficult, because Swift doesn't let you add integers and doubles to a string.

At this point your result may no longer fit in the results pane, so either resize your window or hover over the result and click the + button that appears to have it shown inline.

One of the powerful features of string interpolation is that everything between \( and ) can actually be a full Swift expression. For example, you can do mathematics in there using operators, like this:

var age = 25
"You are \(age) years old. In another \(age) years you will be \(age * 2)."
Interpolating a mathematical expression.
Interpolating a mathematical expression.

이찬희 (MarkiiimarK)
Never Stop Learning.