SwiftUI Tutorial (14 day tutorial), lesson 9, challenge: error in solution

Hi Chris,

In your solution your return in the struct BillSplitter is “totalWithTax/4” That will result in the same value regardless the numPeople input.

My return is “totalWithTax/Double(numPeople)”
Then the calculation with 5 people in the exercise is working.

Hi Hendrik,

Welcome to the code crew community.

Can you show the code that you have. Sounds like something is not quite right.

This is the code that I have for the exercise:

struct TaxCalculator {
    let tax: Double = 0.1
    
    func totalWithTax(inputValue: Double) -> Double {
        let taxAmount = inputValue * tax
        return inputValue + taxAmount
    }
}

struct BillSplitter {
    
    let taxCalculator = TaxCalculator()
    
    func splitBy(subTotal: Double, numberOfPeople: Int) -> Double {
        let totalCost = taxCalculator.totalWithTax(inputValue: subTotal)
        return totalCost / Double(numberOfPeople)
    }
}

let billSplitter = BillSplitter()
let eachMustPay = billSplitter.splitBy(subTotal: 120, numberOfPeople: 5)
let stringValue = String(format: "%.2f", eachMustPay)
print("$\(stringValue)")

Hi,

This is the solution I downloaded in November (official resources, see link below) (and there is no change, I just checked):

As you can see, the return from the struct BillSplitter is fixed to 4 people.
In your code (as well as in my solution), the “4” is exchanged by “Double(numberOfPeople)” or similar.

the return statement at line 17 should be:

return totalWithTax / numPeople

Yes.

My point is:
This is the solution from CodeWithChris.
The solution for students contains the error.

Yep, I see that.

Look at it from the point of view that you were able to debug the code and figure it out by yourself. :+1:

I have notified Chris Ching so it will be corrected when he gets a chance. He is probably busy with the festive season I suspect.

1 Like

Hi Chris,

In line 17, it seems to me that totalWithTax/numPeople will result in a Double being divided by an Int - because in line 12 numPeople is set to type Int.

This same code is present in the solution as well.

Not sure if I am missing as this is my first time with Swift.

regards,
Bhargava

Yes you are right. This was supposed to have been corrected in the solution by wrapping numberOfPeople with Double() like this:

Double(numberOfPeople)

I’ll contact Chris Ching to have that fixed.

Look at it from the point of view that you were able to debug the code and figure it out by yourself. :+1:

Debugging is fun, but still: little reminder that the error is still in the student material I downloaded a few days ago. :wink:

1 Like