Incompatible block pointer types initializing 'CGFloat (^__strong)(CGFloat)' with an expression of type 'double (^)(CGFloat)'

StackOverflow https://stackoverflow.com/questions/15594470

Question

I'm trying to create a block variable that takes a CGFloat argument and returns a CGFloat.

CGFloat (^debt)(CGFloat) = ^(CGFloat myFloat) {
   return myFloat * 444563.4004;
};

What is wrong with this definition? Why am I getting this warning?

Was it helpful?

Solution 2

On iOS (and other 32-bit platforms), CGFloat is an alias for float.

Your literal (444563.4004) is a double, which promotes myFloat to a double and makes the return type of your block double (and not the float you said it would be when you declared debt). Either change the literal to a float (append f to the end of it), or cast it to CGFloat.

OTHER TIPS

Another possible solution is to use a block with an explicit return type:

CGFloat (^debt)(CGFloat) = ^CGFloat (CGFloat myFloat) {
    return myFloat * 444563.4004;
};

to avoid that the compiler tries to "guess" the return type from the return statement.

Compare Creating a Block in "Blocks Programming Topics":

If you don’t explicitly declare the return value of a block expression, it can be automatically inferred from the contents of the block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top