Any way to return value in a block

Hi ,


I have a method retruning boolean value, buy I use block in this method to do network.


And I just want to return true or false in this block.


But I couldnt because there is a error as below.


Return type 'int' must match previous return type 'void' when block literal has unspecified explicit return type


oh.. any way to solve those problem ?


Thanks 😝

Accepted Reply

Presumably you have code like this:

BOOL (^b)(int someParam);

b = ^(int someParam){
    return someParam > 0;
};

and are getting this error on line 3. The issue here is that

someParam > 0
is of type
int
, so the inferred type of the block is
int (^)(int)
, which is not compatible with the type of
b
, that is,
BOOL (^)(int)
.

There are two ways to fix this. First, you could force the type of the block:

b = ^BOOL(int someParam){
    return someParam > 0;
};

Alternatively, you could force the type that you return so that the type of the block in inferred correctly:

b = ^(int someParam){
    return (BOOL) (someParam > 0);
};

IMPORTANT In this second case I added some parens so that the cast applies to the whole result, not to just

someParam
.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Replies

Presumably you have code like this:

BOOL (^b)(int someParam);

b = ^(int someParam){
    return someParam > 0;
};

and are getting this error on line 3. The issue here is that

someParam > 0
is of type
int
, so the inferred type of the block is
int (^)(int)
, which is not compatible with the type of
b
, that is,
BOOL (^)(int)
.

There are two ways to fix this. First, you could force the type of the block:

b = ^BOOL(int someParam){
    return someParam > 0;
};

Alternatively, you could force the type that you return so that the type of the block in inferred correctly:

b = ^(int someParam){
    return (BOOL) (someParam > 0);
};

IMPORTANT In this second case I added some parens so that the cast applies to the whole result, not to just

someParam
.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Thank you so much !


I will try to write more code to show my situation so that other people do not need to presume my code..


Thanks again 🙂