Swift - How to use String interpolation

Introduction

The easiest way to combine the two variables into a string is to use string interpolation.

String interpolation has the following syntax:

\ (variable_name )

The following statement uses string interpolation to combine the value of euro and amount into a single string:

Demo

var euro:Character = "c"
var amount = 1234
var amountStr1 = "\(euro)\(amount)"
print(amountStr1)/*ww  w  .  j  a va2s.  c  om*/

Result

Try to concatenate a string together with a numeric value such as Double or Int, you will get an error:

var amountStr2 = "\(euro)" + amount  //error

Instead, you should explicitly convert the numeric value to a string using the String() initializer:

var amountStr2 = "\(euro)" + String(amount)

Try to concatenate a Character type and an Int type, you will get a compiler error:

var amountStr3 = euro + amount  //error

You should convert both types to String before concatenating them:

var amountStr3 = String(euro) + String(amount)

Related Topic