String interpolation is an extremely convenient way to mix variables, constants, and expressions into a string. It is extremely common to use this within your app. In this tutorial we’ll look at how you can use it in your own app.
let name = "Matthew"
let age = 40
let greeting = "Hello, my name is \(name) and I am not \(age) years old."
print(greeting)
In its simplest form we have a string that contains two constants. Adding a variable, constant, or expression is done by adding a back slash, open bracket, variable/constant/expression, followed by a closing bracket.
If you run this code in the Playground, or in an app, you’ll see “Hello, my name is Matthew and I am not 40 years old.”
You can include an expression as follows:
let correctAge = age + 8
let updatedGreeting = "Hello, my name is \(name) and I am \(correctAge) years old."
print(updatedGreeting)
Leaving the old code in place, and adding this below, you can pass in the “correctAge” variable.
Alternatively you can add the expression inline, although I wouldn’t recommend going too crazy with doing it inline as some items you add in might need more than a simple expression.
let anotherGreeting = "Hello, my name is \(name) and I am \(age + 8) years old."
print(anotherGreeting)
You can also format a number within:
let pi = 3.14159
let formattedPi = "The value of Pi is \(String(format: "%.2f", pi))"
print(formattedPi)
In this example we format the number to have two decimal places which returns a string that is interpolated into the string.
This works with formatting dates or anything that can be added.
String interpolation seems like a relatively boring topic, but given that you’ll use it in many places, its good to know some of the basics associated with it and how it works.
Leave a Reply
You must be logged in to post a comment.