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

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

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

当前回答

斯威夫特4:

let x:Int = 45
let str:String = String(describing: x)

开发者。Apple.com >字符集init(describing:)

String(description:)初始化式是将任何类型的实例转换为字符串的首选方法。

自定义字符串转换

其他回答

弦乐演奏

稍微讲讲性能 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
            }
        }
    }
}

将Unicode Int转换为字符串

对于那些想要将Int转换为Unicode字符串的人,您可以执行以下操作:

let myInteger: Int = 97

// convert Int to a valid UnicodeScalar
guard let myUnicodeScalar = UnicodeScalar(myInteger) else {
    return ""
}

// convert UnicodeScalar to String
let myString = String(myUnicodeScalar)

// results
print(myString) // a

或者:

let myInteger: Int = 97
if let myUnicodeScalar = UnicodeScalar(myInteger) {
    let myString = String(myUnicodeScalar)
}

斯威夫特4:

试图在label中显示没有Optional()字的值。

这里x是一个Int值使用。

let str:String = String(x ?? 0)

我正在使用这个简单的方法

字符串到Int:

 var a = Int()
var string1 = String("1")
a = string1.toInt()

和从Int到String:

var a = Int()
a = 1
var string1 = String()
 string1= "\(a)"
let Str = "12"
let num: Int = 0
num = Int (str)