【问题标题】:Can anyone help me to understand this? ------ ( )? [ ]:[ ] in objectiveC [duplicate]谁能帮我理解这一点? ------ ( )? [ ]:[ ] 在目标 C [重复]
【发布时间】:2012-09-18 07:42:41
【问题描述】:

可能重复:
What does the question mark and the colon (?: ternary operator) mean in objective-c?

    NSString *requestString = (self.isFirstTimeDownload) ? [NSString stringWithFormat:[self.commonModel.apiURLs objectForKey:@"updateNewsVerPOST"],@""] : [NSString stringWithFormat:[self.commonModel.apiURLs objectForKey:@"updateNewsVerPOST"], [[NSUserDefaults standardUserDefaults] objectForKey:@"localnewsupdate"]];

谁能帮我理解这是什么()?和:在Objective-c中? 谢谢!!

【问题讨论】:

标签: objective-c ios


【解决方案1】:

这是一个三元运算符。

例子:

  bool foo(int i)
  {
      if ( i > 5 ) 
          return true;
      else
          return false;
  }

等价于

  bool foo(int i)
  {
      return ( i > 5 ) ? true : false;
  }

您可以省略第一个操作数:x ? : b,在这种情况下,当 x 不为零时,表达式的值为 x,否则为 b。示例:

int i = 1;
i = 2 ? : 3;   // equivalent to i = 2; (because 2 is non zero)
i = YES ? : 3; // equivalent to i = 1; (because YES is 0x01, which is not zero)

【讨论】:

  • @Jano 感谢您添加的额外信息。
【解决方案2】:

这是一个ternary operator

NSString *requestString = ( boolean condition ) ? @"valueIfTrue" : @"valueIfFalse";

【讨论】:

    猜你喜欢
    • 2023-02-06
    • 2020-10-29
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 1970-01-01
    • 2019-01-22
    相关资源
    最近更新 更多