条件运算符没有第二个属性

时间:2014-07-07 09:29:19

标签: objective-c conditional-operator

我意识到当第二个值丢失时,我并不完全理解条件运算符。任何人都可以解释我(并使用if-else语句粘贴等效语句)以下代码:

if (self.root && [data isKindOfClass:[NSDictionary class]]) {
    data = [data objectForKey:self.root] ? : data;
}

2 个答案:

答案 0 :(得分:1)

没有第一个元素的三元运算符,例如

 variable ?: anotherVariable

相同
 (variable != nil) ? variable : anotherVariable

Here是关于Objective-C中三元运算符的一个很好的解释。

答案 1 :(得分:0)

你可以这样做吗

为避免混淆,我们将您的示例代码视为

   if (self.root && [data isKindOfClass:[NSDictionary class]]) {
    myData = [data objectForKey:self.root] ? : data;  
   }

你可以用

替换它
if (self.root && [data isKindOfClass:[NSDictionary class]])
 {
      if([data objectForKey:self.root])
      {
             //if the condition is true (if data is non-nil)
             myData = [data objectForKey:self.root]
      }
      else
      {
           //goes for false (if data is nil)
          myData = data     
      }

 }

对于你的情况,它如下所示

   if (self.root && [data isKindOfClass:[NSDictionary class]]) {
      myData = [data objectForKey:self.root] ? : data; //if the object found for key "self.root" then myData will hav the object for key "self.root" otherwise it "myData" hav "data" 
   }

让我们举一个简单的例子

//for example
 BOOL aBoolValue = NO;
 int num = (aBoolValue == YES) ? 100 : 50; //if aBoolValue is YES then num has 100 otherwise 50
//in the above example num contains 50
相关问题