How to use \() to embed values in Swift

Overview

In Swift, there are times when we need to print the values of a variable in a string or sequence of characters. This can be achieved by using \(). This enables us to easily print the value of a variable inside a string.

Syntax

\(variable)
Syntax of the \() which embeds values of variables

Parameters

variable: This is the variable whose value we want to embed inside a string.

Return value

The value returned is the value of the variable, variable.

Example

// create some variables
var age:Int = 200;
var pi:Float = 3.14;
var role:String = "Developer";
var name:String = "Theodore";
// embed and print values of variables
print("Hi! My name is \(name). I am a \(role).");
print("Did you know I am \(age) years old!");

Explanation

  • Lines 2–5: We create some variables in Swift.
  • Lines 8–9: We print the values of the variables in a sequence of strings using the operator \().

Free Resources