Search code examples
iphoneobjective-cblock

Compilation error on blocks with return type


I have the following block code

    typedef BOOL(^FieldValidationBlock)(NSString *);
FieldValidationBlock aBlock = ^(NSString *input){
    return ([input length] == 10) ;
};

which throws me a compilation error thats tates the return type is int and should be BOOL. when I add a cast it works just fine:

    typedef BOOL(^FieldValidationBlock)(NSString *);
FieldValidationBlock aBlock = ^(NSString *input){
    return (BOOL)([input length] == 10) ;
};

why this happen?


Solution

  • Because BOOL is an objective C type, and the logical comparison operators are standard C. In standard C the return type of comparison operators is an int. This is important to know sometimes, as when you negate a value that you assume to be boolean, but is in fact an int, it's not necessarily going to be what you expect.

    In your example, casting to a BOOL is fine.