开发者

Exit a function in case condition is not satisfied

What is the best way of writing code to exit a function in case condition is not satisfied?

e.g I have a function

-(IBAction) moreDetails
{  
if (condition)  
//condition not satisfied...exit function  
else  
continue with the function 
}

Can i simply write return 开发者_运维知识库?


Yes. "return" returns immediately from the current method/function. If the function/method returns a value then you need to provide a return value: "return NO, return 3, return @"string", and so on.

I generally prefer this structure:

void f()
{
    if ( ! conditionCheck )
        return;
    // long code block
}

to this:

void f()
{
    if ( conditionCheck )
    {
        // long code block
    }
}

because fewer lines are indented


Yes - you should use return. Because your method returns void, no need for anything else. I'd write more, but there's not much else to it :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜