Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Int to String in Swift

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
like image 763
Steve Marshall Avatar asked Jun 11 '14 11:06

Steve Marshall


People also ask

How do I convert an int to a String in Swift?

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.

How do I convert int to char?

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.


2 Answers

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)
like image 185
Shai Avatar answered Oct 12 '22 05:10

Shai


Check the Below Answer:

let x : Int = 45
var stringValue = "\(x)"
print(stringValue)
like image 98
PREMKUMAR Avatar answered Oct 12 '22 04:10

PREMKUMAR