Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...