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

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

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

当前回答

为了在将来节省你的时间和麻烦,你可以做一个Int扩展。通常我会创建一个共享代码文件,在其中放置扩展名、枚举和其他有趣的东西。下面是扩展代码的样子:

extension Int
{
    func toString() -> String
    {
        var myString = String(self)
        return myString
    }
}

之后,当你想将int型转换为字符串时,你可以这样做:

var myNumber = 0
var myNumberAsString = myNumber.toString()

其他回答

let Str = "12"
let num: Int = 0
num = Int (str)

在Swift 3.0中:

var value: Int = 10
var string = String(describing: value)

弦乐演奏

稍微讲讲性能 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 = 45
let string = "\(x)"

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

let text = "\(count) \(count > 1 ? "items" : "item") in the cart. Sum: $\(sum + shippingPrice)"

检查下面的答案:

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