在Swift中将Int转换为字符串
问题描述:
我试图找出如何在Swift中将 Int
转换为 String
。
I'm trying to work out how to cast an Int
into a String
in Swift.
我想出了一个解决方法,使用 NSNumber
但我想知道如何做到这一切在Swift。 / p>
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
答
转换 code>到
字符串
:
let x : Int = 42
var myString = String(x)
c $ c> String 至 Int
:
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
}
或者如果您使用的是Swift 2:
Or if you're using Swift 2:
let x: Int? = Int(myString)