OneBite.Dev - Coding blog in a bite size

Convert Variable From Int To String In Swift

Code snippet for how to Convert Variable From Int To String In Swift with sample and detail explanation

Swift, a powerful and intuitive programming language developed by Apple, provides numerous functionalities. One common task developers need to conquer is variable type conversion, for instance, turning an integer into a string. This article outlines a step by step tutorial on how to achieve that.

Code Snippet: Convert Variable From Int To String In Swift

var integerVariable: Int = 5
var stringVariable: String 

stringVariable = String(integerVariable)
    
print("`integerVariable` as a string is \(stringVariable)")

Code Explanation: Convert Variable From Int To String In Swift

Let’s break down the aforementioned Swift code to understand the process of converting an integer into a string.

The first line of this code begins with the declaration of an integer variable:

var integerVariable: Int = 5

The next line declares a string variable:

var stringVariable: String 

Here, we’re setting up the necessary variables. The value of ‘integerVariable’ is 5 and ‘stringVariable’ is declared to be converted into a string.

Then, you will use the Swift ‘String’ function to convert the integer into a string:

stringVariable = String(integerVariable)

Here, ‘integerVariable’ is wrapped in a String initializer. It triggers the type conversion from ‘Int’ to ‘String’. As a result, ‘stringVariable’ now holds the string representation of ‘integerVariable’.

When printing this variable, you will see that ‘integerVariable’ as a string is ‘5’:

print("`integerVariable` as a string is \(stringVariable)")

This last statement prints the text alongside the string value of ‘integerVariable’, demonstrating the successful conversion from an integer to a string.

In conclusion, you can convert an Int to a String in Swift simply by wrapping the variable you want to convert in a String initializer, as displayed in this tutorial.

swift