这是我现在用来将一个单位的值转换为另一个单位的函数。我正在寻找一个更动态的选择。我想让函数能够从例如:1 公斤转换为盎司,但是我现在这样做的原因我已经定义了每个单位与另一个单位的比较。有没有更简单的方法来做到这一点?
func weightMath(_ input: UITextField, _ textField: UITextField) {
//The math for doing weight calculations. This will also round up the answer to the third decimal.
switch input.tag {
/*
case 0 is for when the user want to calculate from kilogram
case 1 is for when the user want to calculate from ounces
case 2 is for when the user want to calculate from pounds
*/
case 0:
switch textField.tag {
/*
case 0 is for when the user want to calculate to kilogram
case 1 is for when the user want to calculate to ounces
case 2 is for when the user want to calculate to pounds
*/
case 0:
textField.text = String(format: "%.3f", toFloat(input.text!) * 1)
case 1:
textField.text = String(format: "%.3f", toFloat(input.text!) * 35.274)
case 2:
textField.text = String(format: "%.3f", toFloat(input.text!) * 2.205)
default:
break
}
case 1:
switch textField.tag {
/*
case 0 is for when the user want to calculate to kilogram
case 1 is for when the user want to calculate to ounces
case 2 is for when the user want to calculate to pounds
*/
case 0:
textField.text = String(format: "%.3f", toFloat(input.text!) * 0.028)
case 1:
textField.text = String(format: "%.3f", toFloat(input.text!) * 1)
case 2:
textField.text = String(format: "%.3f", toFloat(input.text!) * 0.063)
default:
break
}
case 2:
switch textField.tag {
/*
case 0 is for when the user want to calculate to kilogram
case 1 is for when the user want to calculate to ounces
case 2 is for when the user want to calculate to pounds
*/
case 0:
textField.text = String(format: "%.3f", toFloat(input.text!) * 0.454)
case 1:
textField.text = String(format: "%.3f", toFloat(input.text!) * 16)
case 2:
textField.text = String(format: "%.3f", toFloat(input.text!) * 1)
default:
break
}
default:
break
}
}