我正在尝试乘法
self.tipLable.text = String("\((enterBillAmountTextField.text! as NSString).integerValue * (middleTextField.text! as NSString).integerValue * (0.01))")
但是获取错误二进制运算符*不能应用于Int和Double
类型的操作数我从UITextfields获取值。怎么做这个乘法?
答案 0 :(得分:2)
extension Double {
// Convert Double to currency
var currency: String {
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
return formatter.stringFromNumber(self) ?? "0"
}
}
tipLable.text = [enterBillAmountTextField, middleTextField].reduce(0.01) { $0 * (Double($1.text!) ?? 0) }.currency
略微更清晰的解决方案。添加了“货币”扩展名,因此仍然可以在一行中完成:)。
答案 1 :(得分:0)
这有效
self.tipLable.text = String("\( Double((enterBillAmountTextField.text! as NSString).integerValue) * Double((middleTextField.text! as NSString).integerValue) * 0.01)")
答案 2 :(得分:0)
Swift不知道如何乘以Int和Double。结果应该是Int还是Double?
Swift不会在不同的操作数之间进行隐式类型转换。
如果您希望结果为Double,则两个操作数都应为Double。然后将Double转换为String。
虽然这可以在一个很长的行中简明扼要地表达,但如果你把它分成不同的行,它可能更具可读性和可维护性:
let subTotal = Double(billAmountTextField.text!) ?? 0
let percent = (Double(middleTextField.text!) ?? 0) * 0.01
let tip = subTotal * percent
self.tipLable.text = String(format: "%.2f", tip) // Handle rounding
答案 3 :(得分:-1)
你给出的答案会在某个时刻给你带来噩梦。
尽量让自己以某种方式做事,保证你能够测试它,以及你/或其他人能够理解你在那里做的事情。
/**
Use this function to calculate tip, useful for later testing
- returns: Double Value of the tip you should give
*/
func calculateTip(billAmount billAmount:Double, middleValue:Double) -> Double {
/// Actually calculate Tip if everything is OK
return billAmount * middleValue * 0.01
}
然后在
@IBAction
中确保您在询问之前有正确的数据 你的小费函数
/// If you have bill data, obtain Double value stored there,
/// if something fails, you should return nil
guard let billAmountText = enterBillAmountTextField.text, billAmount = Double(billAmountText) else {
return
}
/// If you have middle value data, obtain Double value stored there,
/// if something fails, you should return nil
guard let middleText = middleTextField.text, middleValue = Double(middleText) else {
return
}
然后你可以调用那个函数
let tip = calculateTip(billAmount: billAmount, middleValue: middleValue).description
//and return in proper format
tipLabel.text = String(format: "%.2f", tip)