Yogesh Chauhan's Blog

How to concatenate variable with string in Swift?

in Swift on March 2, 2020

String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal.

You can use string interpolation in both single-line and multiline string literals. Each item that you insert into the string literal is wrapped in a pair of parentheses, prefixed by a backslash ():


let multiplier = 3
let message = "(multiplier) times 2.5 is (Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"

In the example above, the value of multiplier is inserted into a string literal as (multiplier). This placeholder is replaced with the actual value of multiplier when the string interpolation is evaluated to create an actual string.

The value of multiplier is also part of a larger expression later in the string. This expression calculates the value of Double(multiplier) * 2.5 and inserts the result (7.5) into the string. In this case, the expression is written as (Double(multiplier) * 2.5) when it’s included inside the string literal.

You can use extended string delimiters to create strings containing characters that would otherwise be treated as a string interpolation. For example:


print(#"Write an interpolated string in Swift using (multiplier)."#)
// Prints "Write an interpolated string in Swift using (multiplier)."

To use string interpolation inside a string that uses extended delimiters, match the number of number signs before the backslash to the number of number signs at the beginning and end of the string. For example:


print(#"6 times 7 is #(6 * 7)."#)
// Prints "6 times 7 is 42."

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface #Jan 14 How to display a student’s individual transcript in Colleague? #Jan 11 How to install PuTTY on a MacOS?
You might also like these
Observation of Human Behavior [Shopping Observation Example]MiscellaneousWindow setInterval() Method in JavaScriptJavaScriptSQL ALL OperatorSQL/MySQLUnderstanding the confusing and handy “This” keyword in JavaScriptJavaScriptAND, OR and NOT boolean operators in Envision BasicEnvision BasicHow to animate list items using CSS and JavaScript?CSS