could not find member subscript

2019-07-07 01:41发布

问题:

I am trying to execute the following code and getting the error Could not find member 'subscript on Xcode6

var b:[[Float]] = [[1,2]]

var i2 = 0 // second to last control point
var pointIm1 = CGPoint(x: 0.0,y: 0.0)
var pointI = CGPoint(x: 0.0,y: 0.0)
var pointIp1 = CGPoint(x: 0.0,y: 0.0)
var px:Float = b[0][0] * Float(pointIm1.x) + b[0][0] * Float(pointI.x) + b[0][0] + b[0][0] * Float(pointIp1.x)

Anyone has idea why is giving error

Edit: Do anyone have better idea or i need to create different variables for each subscript as Nate suggested in his answer

//not looks good
var bj0 = b[j][0]
var bj1 = b[j][1]
var bj2 = b[j][2]
var bj3 = b[j][3]


var px:Float = bj0 * Float(pointIm1.x) + bj1 * Float(pointI.x) + bj2 + bj3 * Float(pointIp1.x)

回答1:

It isn't a problem with the subscript - Swift gets into trouble when trying to parse longer multi-item expressions like your final line. In a playground I get this error:

expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions

You'll need to refactor that line to get past this limitation - something like:

let b00 = b[0][0]
var px: Float = b00 * Float(pointIm1.x) + b00 * Float(pointI.x) + b00 + b00 * Float(pointIp1.x)

You could probably just break it up into two steps, like this:

var px:Float = bj0 * Float(pointIm1.x) + bj1 * Float(pointI.x)
px += bj2 + bj3 * Float(pointIp1.x)


回答2:

It looks like a compiler bug. I tried this expression (obtained from yours, and removing all multiplications):

var px:Float = b[0][0] + b[0][0]  + b[0][0] + b[0][0] 

and it fails, whereas this:

var px:Float = b[0][0] + b[0][0] + b[0][0] 

works.

So Nate Cook's answer is correct, it's the compiler getting into trouble.

More tests - using a unidimensional array, this works:

var c:[Float] = [1.0, 2.0]
var px2: Float = c[0] + c[0] + c[0] + c[0] + c[0]

but this doesn't

var px2: Float = c[0] + c[0] + c[0] + c[0] + c[0] + c[0] // Cannot invoke '+' with arguments of type '($T28, $T32)'

Note that your expression can be refactored as:

var px:Float = b[0][0] * (Float(pointIm1.x) + Float(pointI.x) + 1.0 + Float(pointIp1.x))


标签: ios swift xcode6