OneBite.Dev - Coding blog in a bite size

Format A String In Swift

Code snippet for how to Format A String In Swift with sample and detail explanation

Swift programming language has made formatting a string quite simple and straightforward. In this article, you will learn how to format a string in Swift with a step-by-step explanation of the code.

Code snippet for Formatting a String in Swift

Let’s start with a typical scenario where we might want to format a string. Suppose you have a string that contains placeholders and you want to replace them with specific values. Swift’s string interpolation feature is designed exactly for this type of scenario.

Here is a sample code snippet that demonstrates how to format a string in Swift:

let name = "John"
let age = 25
let formattedString = "Hello, my name is \(name) and I am \(age) years old."
print(formattedString)

When executed, this Swift code will output: “Hello, my name is John and I am 25 years old.”

Code Explanation for Formatting a String in Swift

Let us break down the code to understand how string formatting works in Swift.

  1. The first two lines of our code are straightforward; we declare two variables: name and age. name is of type String, and it’s initialized with the value “John”. age is of type Int, and it’s initialized with the value 25.

    let name = "John"
    let age = 25
  2. The next step is where we perform the string formatting. Swift allows us to include the value of variables directly in a string through a process known as string interpolation. This is done by wrapping the name of the variable in parentheses, preceded by a backslash (). In our example, we use (name) to insert the name “John” and (age) to insert the age 25.

    let formattedString = "Hello, my name is \(name) and I am \(age) years old."
  3. The last line of the code snippet simply prints the formatted string to the console.

    print(formattedString)

That’s all there is to it! String formatting in Swift is simple and straightforward, once you understand the concept of string interpolation. This feature is quite powerful and can help make your code cleaner and more readable, particularly when working with strings that involve dynamic data.

swift