0
0
Swiftprogramming~5 mins

String interpolation in Swift

Choose your learning style9 modes available
Introduction

String interpolation lets you easily put values like numbers or text inside a string. It helps make messages that change based on data.

Showing a user's name inside a welcome message.
Displaying the result of a calculation in a sentence.
Creating a sentence that includes the current date or time.
Building a message that includes values from variables.
Syntax
Swift
let message = "Hello, \(name)!"

Use \( ) inside a string to insert a value or expression.

You can put variables, math, or function calls inside the parentheses.

Examples
Insert a number variable inside a string.
Swift
let age = 25
let greeting = "I am \(age) years old."
Insert a text variable inside a string.
Swift
let name = "Anna"
let welcome = "Welcome, \(name)!"
Insert a math expression inside a string.
Swift
let a = 5
let b = 3
let sum = "Sum is \(a + b)"
Sample Program

This program creates a message that includes a name and number using string interpolation, then prints it.

Swift
let userName = "Sam"
let items = 3
let message = "Hello, \(userName)! You have \(items) new messages."
print(message)
OutputSuccess
Important Notes

String interpolation works only inside double quotes " ".

You can put any Swift expression inside \( ), not just variables.

It helps avoid long string concatenations with + signs.

Summary

String interpolation inserts values inside strings easily.

Use \( ) inside double quotes to add variables or expressions.

It makes building dynamic messages simple and readable.