你好,我有一个关于这段代码的问题:
1)
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
2)
let height = "3"
let number = 4
let hieghtNumber = number + Int(height)
第一部分工作得很好,但我不明白为什么第二部分不行。我收到错误“二元运算符“+”不能应用于两个 int 操作数”,这对我来说没有多大意义。谁能帮我解释一下?
最佳答案
1) 第一个代码有效是因为 String
有一个 init 方法接受 Int
.然后上线
let widthLabel = label + String(width)
您正在将字符串与 +
连接起来运算符,创建 widthLabel
.
2) Swift 错误消息可能具有误导性,实际问题是 Int
没有 init
采用 String
的方法.在这种情况下,您可以使用 toInt
String
上的方法.这是一个例子:
if let h = height.toInt() {
let heightNumber = number + h
}
你应该使用 and if let
检查 String
的语句可以转换为 Int
自 toInt
将返回 nil
如果失败;在这种情况下强制展开会使您的应用程序崩溃。请参阅以下示例,了解如果 height
会发生什么情况无法转换为 Int
:
let height = "not a number"
if let h = height.toInt() {
println(number + h)
} else {
println("Height wasn't a number")
}
// Prints: Height wasn't a number
Swift 2.0 更新:
Int
现在有一个初始化程序,它接受 String
,制作示例 2(见上文):
if let h = Int(height) {
let heightNumber = number + h
}
关于swift - 二元运算符 + 不能应用于两个 int 操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30349648/