I'm trying to work out how to cast an Int
into a String
in Swift.
I figure out a workaround, using NSNumber
but I'd love to figure out how to do it all in Swift.
let x : Int = 45
let xNSNumber = x as NSNumber
let xString : String = xNSNumber.stringValue
To convert an Int value to a String value in Swift, use String(). String() accepts integer as argument and returns a String value created using the given integer value.
Example 1: Java Program to Convert int to char char a = (char)num1; Here, we are using typecasting to covert an int type variable into the char type variable. To learn more, visit Java Typecasting. Note that the int values are treated as ASCII values.
Converting Int
to String
:
let x : Int = 42
var myString = String(x)
And the other way around - converting String
to Int
:
let myString : String = "42"
let x: Int? = myString.toInt()
if (x != nil) {
// Successfully converted String to Int
}
Or if you're using Swift 2 or 3:
let x: Int? = Int(myString)
Check the Below Answer:
let x : Int = 45
var stringValue = "\(x)"
print(stringValue)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With