We've already learned a lot about Strings In Swift in this article. This is a continuation to that article, in which we'll briefly discuss String Interpolation in Swift.
Let's get started.
In this article, we'll be looking at a very useful technique called String Interpolation, which we'll use often while programming in Swift.
A lot of the time, we'll encounter a situation in which we'll need to insert some values inside a string. For example, look at the following code snippet:
var myAge = 19
Here, I have a variable
myAge that has an integral value of 19.
Suppose I have to print a string that says: "I am 19 years old".
One of the possible ways of doing it is:
print("I am 19 years old")
A simple, naive approach, without the utilization of the variable we had declared earlier.
But in case we have to update our age, we'll have to manually update 19 everywhere we have used this statement inside our program.
Another way of doing it will be something like this:
print("I am", myAge," years old")
This is a better approach than the previous as even if we assign a new variable to variable
myAge, it'll automatically get updated here.
This is because we have introduced the variable inside the string, separated from the string with commas, whereas in the previous case, we'd have to manually change and update the string.
This would have to be done every time and everywhere in the program as the variable was not involved inside the string.
A better and more efficient way of doing the same thing, without separating the strings and variables with commas is with String Interpolation.
In Swift, to interpolate a value inside a string, we can wrap the value in parentheses, and write a backslash \ before the parentheses.
Here the value can be a variable, a constant, or any other kind of data type or operation in Swift.
var myAge = 19 print("I am \(myAge) years old")
We can treat the variable
myAge as raw Swift code and perform any kind of operation to it as well.
var myAge = 19 print("I will be \(myAge+1) years old next year.")
And as you guessed, the output will be: I will be 20 years old next year.
This was all about the very easy and important concept of String Interpolation in Swift.
Thank you for reading this far.
Check out more at ishaanbedi.me