简体   繁体   中英

Using block with ternary operator in Objective-C

Is there a way to use blocks with the ternary operator in Objective-C?

I'm trying to do something like:

[self evaluate] ? ^{
    // do somethings
} : ^{
    // do something else
}

You're getting result unused because you don't assign your block at all

void (^someBlock)(void) = [self evaluate] ? ^{
    // do somethings
} : ^{
    // do something else
};

someBlock();

Update

As @MartinR pointed out, if you'd prefer to get even more convoluted, you could call the block in the ternary:

[self evaluate] ? ^{
    // do somethings
}() : ^{
    // do something else
}();

Update 2

The actual convolution @MartinR was suggesting:

([self evaluate] ? ^{
    // do somethings
} : ^{
    // do something else
})();

NOTE

As @zaph and @joshCaswell have pointed out in the comments, while this is technically correct (the best kind of correct) it is perhaps not the best practice. In the case of executing the block inline as mentioned in the updates, it is particularly strange as mentioned in the answer here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM