我正在尝试计算账单上的总金额,但看不到如何去做。这是我正在学习的教程中写的,因为我正在学习SwiftUI。
有关如何操作的任何提示?
username sum_all_games_points
John 32 -- This is the sum of (10 + 8 + 7 + 3 + 4)
Martha 2 -- Only one game played on game2
Adam 10 -- 9 points from game1 and 1 point from game2
这是我正在做的一个教程,这是您可以做的额外挑战。我认为做额外的挑战会很好,我尝试了不同的方法,但只在SwiftUI中收到错误消息。
答案 0 :(得分:0)
一种方法是重构totalPerPerson
的计算方式。如果您查看一下计算,实际上是在计算账单的总数。
var totalPerPerson: Double {
let peopleCount = Double(numberOfPeople + 2)
let tipSelection = Double(tipPercentages[tipPercentage])
let orderAmount = Double(checkAmount) ?? 0
let tipValue = orderAmount / 100 * tipSelection
let grandTotal = orderAmount + tipValue // <- this is the total amount of the bill
let amountPerPerson = grandTotal / peopleCount
return amountPerPerson
}
如果您创建一个名为grandTotal
的附加变量,则可以重构totalPerPerson
变量以使用此新变量。
// this is the code used in the totalPerPerson to calculate the grandTotal
var grandTotal: Double {
let tipSelection = Double(tipPercentages[tipPercentage])
let orderAmount = Double(checkAmount) ?? 0
let tipValue = orderAmount / 100 * tipSelection
let grandTotal = orderAmount + tipValue
return grandTotal
}
// The totalPerPerson uses the above grandTotal variable to calculate its value
var totalPerPerson: Double {
let peopleCount = Double(numberOfPeople + 2)
let amountPerPerson = grandTotal / peopleCount
return amountPerPerson
}
然后由您决定如何在屏幕上显示它。