Gralex
Gralex

Reputation: 4485

Trouble with block, iOS

I get this error when trying to define and assign a block:

int (^bl)(int) = ^(int k)
{
    [_self c2:k]; // incompatible block pointer types initializing 'int (^)(int)' with an expression of type 'void (^)(int)'
};

This is from a blocks tutorial:

What is going on?

Upvotes: 1

Views: 111

Answers (1)

Mattias Wadman
Mattias Wadman

Reputation: 11425

Change the return type of bl from int to void.

void (^bl)(int) = ^(int k) {
    [_self c2:k];
};

If you look at the language specification for blocks you will see what's going on:

The return type is optional and is inferred from the return statements. If the return statements return a value, they all must return a value of the same type. If there is no value returned the inferred type of the Block is void; otherwise it is the type of the return statement value.

In Apples example case the return type will be the type of num * multiplier which is int matching the return type of the block variable myBlock.

But in your case there is no return statements so the return type will be void which does not match the return type of the block variable bl.

Upvotes: 1

Related Questions