是否可以使这个无效代码更简单
它基本上从2个盒子中获取2个值,具体取决于所选的 操作员进行计算。
@IBAction func enterpressedinbox2(sender: AnyObject) {
let value1toint = Int(value1.stringValue)
let value2toint = Int(value2.stringValue)
var result = 0;
if operatorselection.stringValue == "+"{
result = value1toint! + value2toint!
}
if operatorselection.stringValue == "-"{
result = value1toint! - value2toint!
}
if operatorselection.stringValue == "*"{
result = value1toint! * value2toint!
}
if operatorselection.stringValue == "/"{
result = value1toint! / value2toint!
}
let resultinttostring = String(result)
resultlabel.stringValue = ": " + resultinttostring
view.window!.title = "The result is " + resultinttostring
}
答案 0 :(得分:0)
我会用函数字典做这样的事情:
@IBAction func enterpressedinbox2(sender: AnyObject) {
let ops : [String: (Int, Int)->Int] = [ "+" : { x, y in x + y },
"-" : { x, y in x - y },
"*" : { x, y in x * y },
"/" : { x, y in x / y } ]
if let x = Int(value1.stringValue),
let y = Int(value2.stringValue),
let f = ops[operatorselection.stringValue] {
let result = String(f(x, y))
resultlabel.stringValue = ": " + result
view.window!.title = "The result is " + result
}
}