In the Swift "Tour" documentation, there's an exercise where you build on the following function to average a set of numbers:
func sumOf(numbers: Int...) -> Int { var sum = 0 for number in numbers { sum += number } return sum }
I can make this work using something like the following:
func averageOf(numbers: Double...) -> Double { var sum: Double = 0, countOfNumbers: Double = 0 for number in numbers { sum += number countOfNumbers++ } var result: Double = sum / countOfNumbers return result }
My question is, why do I have to cast everything as a Double to make it work? If I try to work with integers, like so:
func averageOf(numbers: Int...) -> Double { var sum = 0, countOfNumbers = 0 for number in numbers { sum += number countOfNumbers++ } var result: Double = sum / countOfNumbers return result }
I get the following error: Could not find an overload for '/' that accepts the supplied arguments
When dividing two numbers of the same type (integers, doubles, etc.) the result will always be of the same type (so 'int/int' will always result in int). In this case you have double var = integer result which casts the integer result to a double after the calculation in which case the fractional data is already lost.
You need to use "/" to divide, not "\".
The OP seems to know how the code has to look like but he is explicitly asking why it is not working the other way.
So, "explicitly" is part of the answer he is looking for: Apple writes inside the "Language Guide" in chapter "The Basics" -> "Integer and Floating-Point Conversion":
Conversions between integer and floating-point numeric types must be made explicit
you just need to do this:
func averageOf(numbers: Int...) -> Double { var sum = 0, countOfNumbers = 0 for number in numbers { sum += number countOfNumbers++ } var result: Double = Double(sum) / Double(countOfNumbers) return result }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With