Convert int to string and vice-versa in Swift

In this tutorial, we will learn how to convert any integer to a string and string to an integer using various approaches in Swift.

Convert Int to string in Swit

To work on this we will first initialize an integer value and convert it into a string using various methods and approaches and then try to print its type.

Method 1- Using typecast String()

This method converts the given integer to a string using String() function. We can implement it as-

let a : Int = 342
var str = String(a)



Here we have assigned integral value 342 to an integer “a” and then explicitly converted it into a string and then tried to print its output.

Method 2- Using the conversion

This method uses the “\(a)” to convert the integer to a string. The approach would be the same as above-

var q = Int()
q = 123
var string1 = String()
string1 = "\(q)"



So this method just converted the given integer into a string and stored it in the variable str1 and we have also printed the type to be sure of the type.

Convert string to int in Swift

This method is similar to the above as it first declares a string and then converts it into an integer and we will print the type of the variable to get assured of our task is done right.

Method 1- Using typecast Int()

This method is inbuilt into Swift which results in the output in an integer. The snippet part is as-

let str1="CodeSpeedy"
var int=Int(str1)



The given string “CodeSpeedy” is converted into the string using Int() method and then the output prints an integer.

So we have discussed overall 2 methods of converting an integer into a string and 1 method of converting a string into an integer. I hope you liked reading the tutorial.

Leave a Reply

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