Home > Articles > Programming > General Programming/Other Languages

  • Print
  • + Share This
This chapter is from the book

Merging Variables into a String

When you want to combine a variable in a string there is a special syntax for that. Take an example in which you have a variable message and you want to mix it into a string. In Objective-C you would do something like this:

[NSString stringWithFormat:@"Message was legit: %@", message];

In JavaScript you would do something like this:

"Message was legit:" + message;

In Python you would do something like this:

"Message was legit: %s" % message

In Ruby you would do something like this:

"Message was legit: #{message}"

In Swift you do something like this:

"Message was legit: \(message)"

You use this syntax of \() to add a variable into a string. Of course, this will interpret most things you put in between those parentheses. This means you can add full expressions in there like math. For example:

"2 + 2 is \(2 + 2)"

This makes it very simple to add variables into a string. Of course, you could go the old-school way and concatenate strings together with the plus operator. In most situations you don’t need to do this because the \() makes things so much easier. One thing to remember is that Swift has strict type inference, so if you try to combine a String with an Int, Swift will complain. The error it gives is not the easiest to decipher. For example:

"2 + 2 is " + (2 + 2)

This returns the following error (depending on your version of Swift and how you are running it):

<stdin>:3:19: error: binary operator '+' cannot be
applied to operands of type 'String' and 'Int'
print("2 + 2 is " + (2 + 2))
~~~~~~~~~~~ ^ ~~~~~~~
<stdin>:3:19: note: overloads for '+' exist with these
partially matching parameter lists: (Int, Int),
(String, String), (UnsafeMutablePointer<Memory>,
Int), (UnsafePointer<Memory>, Int)
print("2 + 2 is " + (2 + 2))

What this means is that you can’t mix Strings and Ints. So you have to convert the Int to a String.

"2 + 2 is " + String(2 + 2)

This works because you are now combining a String and an Int. One of the most important things to keep in mind when writing Swift is that you’ll often do a lot of type conversion to deal with the strict typing.

  • + Share This
  • 🔖 Save To Your Account