Error404 Error404 - 4 days ago 5
iOS Question

Swift 3 error: "Binary operator '/' cannot be applied to two 'int' operands"

I know that there is a question with the same title but I think it is a different problem because I cannot solve it with the solutions provided. The question related is: Binary operator '/' cannot be applied to two (Int) operands. I also have looked at the question that is supposed to be the original.

But I got this error only trying to use a variable inside

UIColor
function:

Work

UIColor(red: 74/255, green: 24/255, blue: 141/255, alpha: 1)


Does not work

var colorRGB = 74
UIColor(red: colorRGB/255, green: 24/255, blue: 141/255, alpha: 1)


So I cannot understand why my error happens. It throws me the following error:


Binary operator '/' cannot be applied to two 'int' operands


I thought that it would be the same because is just the same value in both cases but I am getting that error instead. I think that in the first example there are also two ints values and it does not throw that error.

What can I do to use a variable inside my function?

Thanks in advance!

Answer

The UIColor constructor takes four CGFloat parameters.

UIColor(red: 74/255, green: 24/255, blue: 141/255, alpha: 1)

compiles because CGFloat conforms to the ExpressibleByIntegerLiteral protocol. From the context the compiler tries to make 74/255 a CGFloat, and interprets all the numbers as CGFloat literals, and / as the CGFloat division operator.

That does not work with

var colorRGB = 74
UIColor(red: colorRGB/255, green: 24/255, blue: 141/255, alpha: 1)

There is no context for the 74 literal, so that it is taken as an Int by default. But there is no suitable division operator to make colorRGB/255 a CGFloat.

You have to define the variable explicitly with the correct type:

var colorRGB: CGFloat = 74
Comments