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

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

문제

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?

도움이 되었습니까?

해결책 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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top