Swift binary operator '+' cannot be applied to two CGFloat operands

Colliot picture Colliot · Jun 6, 2015 · Viewed 37.2k times · Source

I am writing a function in Swift to detect which hexagon I am clicking on. But I ran into a peculiar error message stating that I cannot add two CGFloats. Whatever I did, e.g. changing let to var, declare and assign separately, did not work. I guess there must be something else wrong, but I cannot find it. The code is as follows:

func pointToCoordinate(position: CGPoint) -> (Int, Int) {
        var gridHeight = 2 * singleRadius / sqrt(CGFloat(3)) * 1.5
        var gridWidth = 2 * singleRadius
        var halfWidth = singleRadius

        var relativePosition = CGPoint(x: position.x - totalRadius / 2, y: position.y - totalRadius / 2)
        println((relativePosition.y / gridHeight))
        var row = -(cgfloatToInt)(relativePosition.y / gridHeight)
        var column: Int

        println((relativePosition.x + halfWidth * CGFloat(row + 1)) / (gridWidth))
        column = cgfloatToInt((relativePosition.x + halfWidth * CGFloat(row + 1)) / (gridWidth))

//        var innerY: CGFloat = CGFloat(relativePosition.y) + CGFloat(gridHeight * row)
        var innerX = relativePosition.x
        var innerY = relativePosition.y

        innerY = innerY - CGFloat(gridHeight * row)

        println((innerX, innerY))
        return (column, row)
    }

Error Message

Answer

vacawama picture vacawama · Jun 6, 2015

The error message is wrong. The problem is that you are trying to multiply an Int and a CGFloat.

Replace:

innerY = innerY - CGFloat(gridHeight * row)

with:

innerY = innerY - gridHeight * CGFloat(row)

The answer above is for the current version of your code. For the commented out version that corresponds to the error message you posted:

Replace:

var innerY: CGFloat = CGFloat(relativePosition.y) + CGFloat(gridHeight * row)

with

var innerY: CGFloat = CGFloat(relativePosition.y) + gridHeight * CGFloat(row)