Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I divide integers in swift?

Tags:

swift

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

like image 760
Jack James Avatar asked Jun 12 '14 09:06

Jack James


People also ask

Can INT integers be divided?

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.

What is the divide symbol in Swift?

You need to use "/" to divide, not "\".


2 Answers

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

like image 177
Jens Wirth Avatar answered Oct 11 '22 13:10

Jens Wirth


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 } 
like image 36
Davide Rossetto Avatar answered Oct 11 '22 13:10

Davide Rossetto