Search code examples
iosswiftarraylistsizeofcgfloat

sizeof() gives an error for array argument


Face an error while converting old Objective C code in swift, which is not resolved after trying all other solutions.

Objective C:

CGPoint graphPoint[] = { {0.0, 0.0}, {0.0, 20.0}, {20.0, 20.0}, {10.0, 0.0} };
CGFloat radius = 0.0;
for (int i = 0; i < sizeof(graphPoint) / sizeof(CGPoint); i++) {
    CGPoint a = graphPoint[i];
    CGFloat b = sqrt( pow(a.x - point.x, 2.0) + pow(a.y - point.y, 2.0) );
    if (b > radius) {
        radius = b;
    }
}

Ignore point variable it comes as an method argument.

The point here is sizeof gives an error in Swift code. I tried making as much easy and possible to understand swift compiler still no success.

Swift Code:

let graphPoint = [[0.0, 0.0], [0.0, 20.0], [10.0 20.0], [10.0, 0.0]]
let radius = CGFloat(0.0)
var pointLimit : Int = sizeof(graphPoint) / sizeof(CGPoint)

for var index = 0; index < pointLimit; index++ {
    let a = graphPoint[index]
    let b = sqrt(pow(a.x - point.x, 2.0) + pow(a.y - point.y, 2.0))
    if b > radius {
            radius = b
    }
}

Here if you can see in Objective C code - It is not possible to use sizeof() directly in for loop. So I created new variable pointLimit to simplify the complexity.

Still the line var pointLimit : Int = sizeof(graphPoint) / sizeof(CGPoint) shows an error

binary operator / cannot be applied to two int operands

I understand the error but not able to simplify it.


Solution

  • You can iterate through the array like this:

        let graphPoint = // ...
        var radius = CGFloat(0.0)
    
        for a in graphPoint {
            let b = sqrt(pow(a.x - point.x, 2.0) + pow(a.y - point.y, 2.0))
            if b > radius {
                radius = b
            }
        }
    

    I often have this error "operator X cannot be applied to two Y operands", and usually the problem comes from somewhere else, in this particular case it's because Swift sizeof uses the type and not the var as Glenn said.