gpt4 book ai didi

swift - 学习 Swift 尝试了解如何使代码更简单

转载 作者:行者123 更新时间:2023-11-30 13:50:56 27 4
gpt4 key购买 nike

是否可以使这个无效代码更简单

它基本上从 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
}

最佳答案

我会用函数字典做这样的事情:

@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
}
}

关于swift - 学习 Swift 尝试了解如何使代码更简单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34286511/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com