Learn Courses My Dashboard

Lesson 9 Challenge (14 day Challenge)

I think I got everything correct but I don’t know how to convert an int to a double for the second part of the challenge. I know I need to divide subtotal by the int numPeople, but don’t know how to go about it. Any advice?

Here is the code that I have already.

//Challenge 1
struct TaxCalculator
    private let tax = 0.10
    func totalWithTax(amount:Double) -> Double
        return amount + (amount * tax)

//Challenge 2
struct BillSplitter
    func splitBy(subtotal:Double, numPeople:Int) -> Double
        let total = TaxCalculator().totalWithTax(amount: subtotal)
        return (total / numPeople)

//Challenge 3
let start = BillSplitter()
print(start.splitBy(subtotal: 120, numPeople: 5))

easiest way is to just typecast it by doing Int(numPeople)

When I did this challenge I just made numPeople a Double. A Double would read 5 as 5.0 so it works even though numPeople will never really be anything but a whole number.

That approach does solve the error, I don’t recall typecasting being mentioned in any of the previous lessons but it does make sense. I think when you were saying typecast Int(numPeople), I think you meant Double(numPeople) as numPeople being passed in is already an int and converting an int to an int causes conflicts with the double parameter subtotal.

That is one way around it, but in practice using a double in place of an int could cause problems if the value of said int is really large. The difficulty with expecting numPeople to always be a whole number is a bit flawed. A user entering input to a program could choose to enter invalid data instead and cause the program to crash.

well I guess that was a newbie error. You are correct! thanks for the information. I won’t make that error again.

No problem, even I make some of those mistakes at times. Sometimes it is difficult to know what the data type should be at the period of time that you create the program. Its only after you start testing the variables themselves with different types of input that you kind of get a sense that maybe this data value should be a bit different.

You might think well this should be a bool at one point in time since I only have limited data that I need to check against and as the program grows, you might think well a bool a bit too limited as I have more types of data that I am checking for so I will convert it to a byte or a short and go from there.

oh thats true Double should be multiplied by a Double so it will produce a double… otherwise it just results in an Int