swift – 二进制运算符不能应用于两个int操作数
发布时间:2020-12-14 05:37:16 所属栏目:百科 来源:网络整理
导读:嗨,我有一个关于这段代码的问题: 1) let label = "The width is "let width = 94let widthLabel = label + String(width) 2) let height = "3"let number = 4let hieghtNumber = number + Int(height) 第一部分工作很好,但我不明白为什么第二个不是.我得到
嗨,我有一个关于这段代码的问题:
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有一个使用Int的init方法.然后就行了
let widthLabel = label + String(width) 您将串联字符串与操作符一起创建widthLabel. 2)Swift错误消息可能会引起误导,实际问题是Int没有一个接受String的init方法.在这种情况下,您可以使用String上的toInt方法.以下是一个例子: if let h = height.toInt() { let heightNumber = number + h } 你应该使用,如果let语句检查String可以转换为Int,因为如果ItInt失败则返回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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容