在iOS中使用逻辑运算符(OR/AND,...)

问题描述:

我是编程的新手, 我需要验证if条件中的几个表达式,并且它们两个都返回true时只需要做一些工作。在iOS中使用逻辑运算符(OR/AND,...)

我知道我可以做到这一点使用逻辑运算符,但我不知道逻辑运算符是如何工作的。

对此的任何帮助将非常感激。

非常感谢。

+1

你问的if语句是如何工作的? – HashtagMarkus 2014-12-02 13:58:10

+0

是的,我已经更新了我的问题,并添加了一些关于我的需求的详细信息。 – 2016-11-30 11:53:49

使用逻辑运算符是最好的,多个条件。

例如

INT firstValue = 10; int sencondValue = 16;

// OR operator , retursn TRUE is any of given condtion is true. 
if (firstValue==10 || sencondValue==13 || firstValue>=5) { 
    NSLog(@"True"); 
} 
else 
{ 

NSLog(@"False"); 


} 
//above are 3 condtions in one statement , if any condition is true , result is true 

// AND operator , retursn TRUE is all of given condtion are true and flase if any on the given conditions are false. 

if (firstValue==10 && sencondValue==13 && firstValue>=5) { 
    NSLog(@"True"); 
} 
else 
{ 

    NSLog(@"False"); 


} 

使用短路逻辑和操作员...

实施例1

if (1 == 1 && 2 == 2) { 
    // statements that will always execute 
} 

实施例2

boolean firstCondition = YES; 
boolean secondCondition = NO; 
boolean thirdCondition = YES; 

if (firstCondition && secondCondition && thirdCondition) { 
    // As secondCondition is false this will never execute (and thirdCondition will never be evaluated) 
} 

使用逻辑和操作员的陈述所限只有当第一和第二条件评估为真时,花括号才会执行。另外,如果第一个条件是错误的,第二个条件甚至不会被评估,因此名称短路。

在许多编程语言中,都有可用的逻辑运算符。

好像你正在寻找AND操作:

if (conditionA && conditionB) { 
    // conditional code 
} 

更多信息请参见Wikipedia: Logical operators in C