Divide ints into doubles using Swift

swift

Solution

If you want to return a Double you should deal with Doubles in your function. Change sum and i to Doubles (0.0 vs 0) and convert each number to a double. Like this:

func avg(numbers: Int...) -> Double {
    var sum = 0.0; //now implicitly a double
    var i = 0.0;
    for number in numbers {
        sum += Double(number); //converts number to a double and adds it to sum. 
        ++i;
    }
    return sum / i;
}
avg(42, 597, 12);

Integer and Floating-Point Conversion

Conversions between integer and floating-point numeric types must be made explicit:

let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = Double(three) + pointOneFourOneFiveNine
// pi equals 3.14159, and is inferred to be of type Double

Here, the value of the constant three is used to create a new value of type Double, so that both sides of the addition are of the same type. Without this conversion in place, the addition would not be allowed.

The reverse is also true for floating-point to integer conversion, in that an integer type can be initialized with a Double or Float value:

let integerPi = Int(pi)
// integerPi equals 3, and is inferred to be of type Int

Floating-point values are always truncated when used to initialize a new integer value in this way. This means that 4.75 becomes 4, and -3.9 becomes -3.

Problem

``` func avg(numbers: Int...) -> Double { var sum = 0; var i = 0; for number in numbers { sum += number; ++i; } return sum / i; } avg(42, 597, 12); ``` The line `return sum / i` results in an error `Could not find an overload for '/' that accepts the supplied arguments.` What am I supposed to be doing here?

Original source