-->

Bug in Swift array subscript indexing?

2019-07-28 18:26发布

问题:

I've isolated some Swift code from my project that can be pasted into a Playground. It produces an error "Could not find an overload for '+' that accepts the supplied arguments" both in normal Xcode editing and the Playground. The error refers to the last (non-trivial) line.

import UIKit

let points = 40
let max = points-1

let L = 10.0
let Deltat = 0.01
let Deltax = L/Double(points)

var a = [Double](count: points, repeatedValue: 0.0)
var b = [Double](count: points, repeatedValue: 0.0)
var c = [Double](count: points, repeatedValue: 0.0)

for i in 1..<max-1
{   //let iPlus1 = i+1
    //let temp = 0.5*Deltat/Deltax
    c[i] = 0.5*(a[i+1] + a[i-1]) + 0.5*Deltat/Deltax * (b[i+1] - b[i-1])
}

If I uncomment the line "let iPlus1..." and make the following edit, Swift accepts the code.

{   let iPlus1 = i+1
    //let temp = 0.5*Deltat/Deltax
    c[i] = 0.5*(a[iPlus1] + a[i-1]) + 0.5*Deltat/Deltax * (b[i+1] - b[i-1])
}

If I uncomment the line "let temp..." and make the following edit, Swift again accepts the code.

{   //let iPlus1=i+1
    let temp = 0.5*Deltat/Deltax
    c[i] = 0.5*(a[i+1] + a[i-1]) + temp * (b[i+1] - b[i-1])
}

Neither of these edits make any sense to me, as both are seemingly trivial substitutions. I am aware that Swift will never implicitly typecast for me. There doesn't seem to be any implicit typecasting attempted in the original code -- all Ints and Doubles are declared as intended. I'm starting to believe this is a bug with the Swift array subscript indexing.

回答1:

This is a known swift bug: long statements generate strange compilation errors. Just split your line in 2 lines, such as:

c[i] = 0.5*(a[i+1] + a[i-1])
c[i] += 0.5*Deltat/Deltax * (b[i+1] - b[i-1])

I found out that happens with more than 4 or 5 arithmetic operations in the same line, but that's not a rule, just a number found with some expression types - it may be different in other cases.

Look for example at this Q&A: Xcode Beta 6.1 and Xcode 6 GM stuck indexing for weird reason and Xcode 6 with Swift super slow typing and autocompletion (this last one actually causes slowness, but solved in the same way, so the root is probably the same)