Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide ints into doubles using Swift

Tags:

swift

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?

like image 912
Mark Tomlin Avatar asked Jun 04 '14 05:06

Mark Tomlin


People also ask

Can you divide double by INT Swift?

You can do that quite simply do that by adding a ". 0" on the end of the Integer you want to convert.

Can you divide ints by doubles?

If either operand is a double, you'll get floating point arithmetic. If both operands are ints, you'll get integer arithmetic. 3.5/3 is double/int, so you get a double.

How do you split two variables in Swift?

To divide a value by another in Swift, use the division operator (/).


3 Answers

Swift doesn't implicitly convert between value types, like we've been used to, so any product of your sum and i variables will have the same type they do. You've let them implicitly be defined as Int, so you'll need to cast their type during the final computation, like so:

return Double(sum) / Double(i)
like image 125
Nate Cook Avatar answered Dec 16 '22 20:12

Nate Cook


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.

like image 34
Connor Avatar answered Dec 16 '22 18:12

Connor


Here's an improved answer, using the friendly power of closures:

func avg(numbers: Int...) -> Double {
    return Double(numbers.reduce(0, +)) / Double(numbers.count)
}
like image 35
Jean Le Moignan Avatar answered Dec 16 '22 18:12

Jean Le Moignan