swift 如何从 Int 转换?到字符串

标签 swift

在 Swift 中,我不能通过以下方式将 Int 转换为 String:

var iString:Int = 100
var strString = String(iString)

但是我的 Int 变量呢? ,那里有错误:Cant invoke 'init' with type '@Ivalue Int?'

例子

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

if (x != null) {
    // Successfully converted String to Int
    //And how do can i convert x to string???
}

最佳答案

您可以使用字符串插值。

let x = 100
let str = "\(x)"

如果x是可选的,您可以使用 optional binding

var str = ""
if let v = x {
   str = "\(v)"
}
println(str)

如果你确定 x永远不会nil ,你可以做一个forced unwrappingoptional value 上.

var str = "\(x!)"

在一条语句中你可以试试这个

let str = x != nil ? "\(x!)" : ""

根据@RealMae 的评论,您可以使用 nil coalescing operator (??) 进一步缩短此代码

let str = x ?? ""

关于swift 如何从 Int 转换?到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28290833/

相关文章:

ios - 如何在不重新加载visibleCell的情况下重新加载collectionView上的数据

swift - 计算平均配速

ios - Firebase 数据库更改时在 iOS 中触发通知

swift - Realm 是否需要显式添加嵌套对象

swift - 如何使用 playerViewController 快速循环播放我的视频?

swift - 如何在 SVProgressHUD 中快速设置全屏?

ios - 如何向 UICollectionView 添加适当的填充?

uitableview - 在 Swift 中的自定义单元格中存储/检索核心数据

swift - 为什么允许我使用继承所述协议(protocol)的结构设置协议(protocol)的只读属性?

ios - 如何在 ios 中使用 Swift 将 tableViewCell 的数据共享到下一个 viewController 而不使用 Storyboard