swift - 二元运算符 + 不能应用于两个 int 操作数

标签 swift sum operands

你好,我有一个关于这段代码的问题:

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 的语句可以转换为 InttoInt将返回 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/

相关文章:

ios - Realm swift : Update an object inside a closure

ios - 在 Swift 中动态创建自定义按钮的实例

python - 我如何总结 Django 模型的内容

Python 条件求和使用日期和条件

c++ - 错误 2296 : '^' : illegal , 左操作数的类型为 'double'

c++ - 在 C++ 中使用重载操作数 "+"重载操作数 "<<"大小写错误

ios - 无法在 swift 上使用谷歌地图绘制 infowindows

ios - UITableView 中单元格之间的大间隙,iOS 错误?

python - 从字典中查找后的同名值求和

c# - 运算符 '||' 不能应用于类型 'object' 和 'bool' 的操作数