Subscribe!!!
Swift Int to String is very easy. There are several ways to perform the operation. Let’s look at the first way, use a String constructor.
Using a String Constructor
In this case to pass from Int to String in Swift we are going to use a constructor. Sample code:
// Using String Constructor.
let number: Int = 10
var numberString = String(number)

This for me is the best way.
Int to String using String Interpolation
Now we are going to use String interpolation. Sample code:
// Using String Interpolation.
let number: Int = 10
var numberString: String = "\(number)"

Using .description
Let’s see now how to use the .description method to convert an Int to a String.

Sample code:
// Using .description.
let number: Int = 10
let numberString = number.description
print("DEBUG: The number is: " + numberString)
Let’s see the result of executing this code.

If you want to see how to do the opposite step, that is, pass from string to int, you can see it in this article.
How to get the length of a string
Well, this is a bonus that I give you. You may be interested in knowing how to get the length of a string.
It’s very easy to do. We have to use .count.

That is all.
Conclusion
I personally prefer to use the String constructor, I think it is the most correct way. If you want to build something, create a constructor, right? Logic is what tells us it makes the most sense. Using the String constructor is the most common way to perform this conversion.
As we have seen in the video we have several ways to perform this casting of types. It is up to us to analyze what is the best way to act according to the problem that we have to solve.
Well, that’s all. I just have to remind you that you can subscribe to my YouTube channel where you can find relevant information about Swift and iOS.
Deja una respuesta