在 Swift 中将 Int 转换为 String [英] Convert Int to String in Swift

查看:80
本文介绍了在 Swift 中将 Int 转换为 String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究如何在 Swift 中将 Int 转换为 String.

I'm trying to work out how to cast an Int into a String in Swift.

我想出了一个解决方法,使用 NSNumber,但我很想弄清楚如何在 Swift 中完成这一切.

I figure out a workaround, using NSNumber but I'd love to figure out how to do it all in Swift.

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

推荐答案

Converting IntString:

Converting Int to String:

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

反之亦然 - 将 String 转换为 Int:

And the other way around - converting String to Int:

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

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

或者,如果您使用的是 Swift 2 或 3:

Or if you're using Swift 2 or 3:

let x: Int? = Int(myString)

这篇关于在 Swift 中将 Int 转换为 String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆