简体   繁体   中英

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

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?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM