zakdances
zakdances

Reputation: 23685

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?

Upvotes: 1

Views: 2833

Answers (2)

Martin R
Martin R

Reputation: 539775

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.

Upvotes: 5

一二三
一二三

Reputation: 21249

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.

Upvotes: 4

Related Questions