我试图弄清楚如何在Swift中将Int转换为字符串。

我想出了一个解决方案,使用NSNumber,但我想弄清楚如何在Swift中做到这一切。

let x : Int = 45
let xNSNumber = x as NSNumber
let xString : String = xNSNumber.stringValue

当前回答

在swift 3.0中,这就是我们如何将Int转换为字符串和字符串转换为Int

//convert Integer to String in Swift 3.0

let theIntegerValue :Int = 123  // this can be var also
let theStringValue :String = String(theIntegerValue)


//convert String to Integere in Swift 3.0


let stringValue : String = "123"
let integerValue : Int = Int(stringValue)!

其他回答

为了完整起见,你还可以使用:

let x = 10.description

或支持描述的任何其他值。

将Int转换为字符串:

let x : Int = 42
var myString = String(x)

而反过来-将String转换为Int:

let myString : String = "42"
let x: Int? = myString.toInt()

if (x != nil) {
    // Successfully converted String to Int
}

如果你使用的是Swift 2或Swift 3:

let x: Int? = Int(myString)

我更喜欢使用字符串插值

let x = 45
let string = "\(x)"

每个对象都有一些字符串表示。这样事情就简单多了。例如,如果您需要创建具有多个值的字符串。你也可以在里面做任何数学运算或者使用一些条件

let text = "\(count) \(count > 1 ? "items" : "item") in the cart. Sum: $\(sum + shippingPrice)"
let Str = "12"
let num: Int = 0
num = Int (str)

exampleLabel。文本=字符串(yourInt)