Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

binary operator '/' cannot be applied to two 'Double' operands

Tags:

swift

While trying to execute this block of code in Swift 3, I encountered the error: binary operator '/' cannot be applied to two 'Double' operands

var array2 = [8, 7, 19, 20]

for (index, value) in array2.enumerated() {
    array2[index] = Double(value) / 2.0
}

Yet this works

var array2 = [Double]()
array2 = [8, 7, 19, 20]

for (index, value) in array2.enumerated() {
    array2[index] = value / 2.0
}

Why doesn't the first block of code work?

like image 648
Simon Tao Avatar asked Nov 26 '16 00:11

Simon Tao


3 Answers

The error is a bit misleading.

In the first set of code, array2 is implicitly declared as an array of Int. So any attempt to assign a value to an index of array2 will require an Int value.

The problem is that Double(value) / 2.0 results in a Double value, not an Int. So the compiler is looking for a version of / that returns an Int. And that version expects two Int parameters. Since you are supplying two Double parameters, you get the error mentioned in your question.

The solution is to either cast the result to an Int or use two Int parameters to /.

var array2 = [8, 7, 19, 20]

for (index, value) in array2.enumerated() {
    array2[index] = Int(Double(value) / 2.0) // cast to Int
}

or

var array2 = [8, 7, 19, 20]

for (index, value) in array2.enumerated() {
    array2[index] = value / 2 // Use two Int
}

The result will be the same in this case. 8 will be replaced with 4. 7 will be replaced with 3, etc.

The second set of code works as-is because you declare the array to be filled with Double so everything matches up with the correct type.

like image 59
rmaddy Avatar answered Oct 17 '22 04:10

rmaddy


For the first one, your array is of type Int hence doing array2.enumerated() gives you value as an Int. When you do this to it, Double(value) / 2.0, the final result returned is of type Double which is incompatible with your array type.

For the second one though, you explicitly declared an array of Double hence array2.enumerated() returns value as a Double so performing the operation works just fine.

like image 23
eshirima Avatar answered Oct 17 '22 03:10

eshirima


rmaddy's answer is correct as to why you are seeing the issue, the implicit Int declaration. For the sake of completeness. There are a couple ways to fix this, casting is one; another not yet mentioned here is to extend Double to include this case, if you need to do this enough you can simply define your own version of Double / Int and control how Swift handles it within your own function.

extension Double {
    static func / (left: Double, right: Int) -> Double {
        return left / Double(right)
    }
}

You can always add another function handling the reverse case an Int / Double, etc...

like image 1
damnabit Avatar answered Oct 17 '22 05:10

damnabit