该代码计算存储在字符串中的变量中的数学表达式的值。该代码可以工作,但我遇到了一个错误,这让我想知道为什么。
如果没有 !
,下面的代码会给出错误警告,指出可选的 Int 已展开。
let operands : [Int] = [Int(split_exp[0])!, Int(split_exp[2])!]
注意:这一行是第三行
为什么在没有 !
的情况下会发生此错误?
// string calculator app. x = multiplication
let expression = "2 x 2"
let split_exp = expression.components(separatedBy: " ")
let operands : [Int] = [Int(split_exp[0])!, Int(split_exp[2])!]
let operation = split_exp[1] // get the operands and the operation
switch operation {
case "+":
print("\(operands[0]) + \(operands[1]) = \(operands.reduce(0, +))")
case "x":
print("\(operands[0]) x \(operands[1]) = \(operands.reduce(1, *))")
default:
print("No answer ")
}
最佳答案
!
运算符强制 Int(myString)
unwrapp。
我想您是 Swift 新手,应该阅读一些有关 Swift 中的 Optionals 的内容。这是一个链接,您可以了解更多信息:
https://medium.com/@agoiabeladeyemi/optionals-in-swift-2b141f12f870
<小时/>简单总结一下,Optional 值可能是 nil
(如果您来自其他语言,则又称为 null
)。这是一种包装您不确定是否已定义的值的方法。
在您的示例中,通过 Int( String )
将 String
转换为 Int
可以返回 nil
例如:
Int("5")
返回 5
Int("r")
返回nil
通过在命令末尾添加 !
,您基本上可以对程序说“我 100% 确定此转换不会失败,并返回一个 Int
”。当您确定可选值不会为零时,这是一种避免处理可选值的方法。
请注意,如果失败,例如 Int("q")!
(将返回 nil),程序就会崩溃
关于arrays - 计算器程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56677684/