在Swift中将Int转换为String

本文翻译自:Convert Int to String in Swift

I'm trying to work out how to cast an Int into a String in Swift. 我正在尝试找出如何在Swift中将Int转换为String

I figure out a workaround, using NSNumber but I'd love to figure out how to do it all in Swift. 我想出了一种解决方法,使用NSNumber但是我很想弄清楚如何在Swift中做到这一点。

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

#1楼

参考:https://stackoom.com/question/1dNSy/在Swift中将Int转换为String


#2楼

Converting Int to String : Int转换为String

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

And the other way around - converting String to Int : 以及另一种方法-将String转换为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: 或者,如果您使用的是Swift 2或3:

let x: Int? = Int(myString)

#3楼

Check the Below Answer: 检查以下答案:

let x : Int = 45
var stringValue = "\(x)"
print(stringValue)

#4楼

for whatever reason the accepted answer did not work for me. 无论出于何种原因,被接受的答案对我都不起作用。 I went with this approach: 我采用了这种方法:

var myInt:Int = 10
var myString:String = toString(myInt)

#5楼

Just for completeness, you can also use: 仅出于完整性考虑,您还可以使用:

let x = 10.description

or any other value that supports a description. 或任何其他支持描述的值。


#6楼

Here are 4 methods: 这是4种方法:

var x = 34
var s = String(x)
var ss = "\(x)"
var sss = toString(x)
var ssss = x.description

I can imagine that some people will have an issue with ss. 我可以想象有些人会遇到ss问题。 But if you were looking to build a string containing other content then why not. 但是,如果您要构建包含其他内容的字符串,那为什么不呢。

你可能感兴趣的:(string,casting,int,converter,swift)