Swift String Interpolation Example

String interpolation is a way to construct new strings that contain constants, variables, literals, and expressions. Each entry of the string literal you inserted is wrapped in parentheses prefixed by a backslash:

let x = 3
let str = "\(x) * 5 = \(Double(x) * 5)"

Below is above code execution result.

3 * 5 = 15.0

In the example above, x is inserted as \(x) into a literal string. This placeholder is replaced with the actual value of x when the string is created for interpolation.

The value of x is also part of the following expression in the string. This expression evaluate Double(x) * 5 and inserts the result (15) into the string.

Please note : Expressions written in parentheses in interpolation strings can not contain unescaped double quotes (“) and backslash (\), and can not contain enter or new line characters.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.