我试图弄清楚如何在Swift中将Int转换为字符串。
我想出了一个解决方案,使用NSNumber,但我想弄清楚如何在Swift中做到这一切。
let x : Int = 45
let xNSNumber = x as NSNumber
let xString : String = xNSNumber.stringValue
我试图弄清楚如何在Swift中将Int转换为字符串。
我想出了一个解决方案,使用NSNumber,但我想弄清楚如何在Swift中做到这一切。
let x : Int = 45
let xNSNumber = x as NSNumber
let xString : String = xNSNumber.stringValue
当前回答
let a =123456888
var str = String(a)
OR
var str = a as! String
其他回答
将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)
弦乐演奏
稍微讲讲性能 UI测试包在iPhone 7(真实设备)与iOS 14
let i = 0
lt result1 = String(i) //0.56s 5890kB
lt result2 = "\(i)" //0.624s 5900kB
lt result3 = i.description //0.758s 5890kB
import XCTest
class ConvertIntToStringTests: XCTestCase {
let count = 1_000_000
func measureFunction(_ block: () -> Void) {
let metrics: [XCTMetric] = [
XCTClockMetric(),
XCTMemoryMetric()
]
let measureOptions = XCTMeasureOptions.default
measureOptions.iterationCount = 5
measure(metrics: metrics, options: measureOptions) {
block()
}
}
func testIntToStringConstructor() {
var result = ""
measureFunction {
for i in 0...count {
result += String(i)
}
}
}
func testIntToStringInterpolation() {
var result = ""
measureFunction {
for i in 0...count {
result += "\(i)"
}
}
}
func testIntToStringDescription() {
var result = ""
measureFunction {
for i in 0...count {
result += i.description
}
}
}
}
检查下面的答案:
let x : Int = 45
var stringValue = "\(x)"
print(stringValue)
有多种方法:
var str1:String="\(23)"
var str2:String=String(format:"%d",234)
不管出于什么原因,这个公认的答案对我不起作用。我采用了这样的方法:
var myInt:Int = 10
var myString:String = toString(myInt)