ios 目标 C 中的短 IF ELSE 语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9805381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Short IF ELSE syntax in objective C
提问by Firdous
Is there any short syntax for if-else statement in objective C like PHP:
在像 PHP 这样的目标 C 中是否有 if-else 语句的简短语法:
if($value)
return 1;
else
return 0;
shorter version:
较短的版本:
return $value?1:0;
回答by Alladinian
Yes.
是的。
Example (pseudo):
示例(伪):
value = (expression) ? (if true) : (if false);
Based on your example (valid code):
根据您的示例(有效代码):
BOOL result = value ? YES : NO;
回答by BoltClock
It's exactly the samein both languages, except you typically don't find $
signs in Objective-C variable names.
这在两种语言中完全相同,除了您通常不会$
在 Objective-C 变量名称中找到符号。
if(value)
return 1;
else
return 0;
return value?1:0;
You should also keep in mind that the conditional operator ?:
isn't a shorthand for an if-else statement so much as a shorthand for a true vs false expression. See the PHP manual.
您还应该记住,条件运算符?:
不是 if-else 语句的简写,而是 true 与 false 表达式的简写。请参阅PHP 手册。
回答by Erzékiel
Surprised that nobody has suggested the following :
令人惊讶的是没有人提出以下建议:
Long version :
if(value) return 1; else return 0;
Small version :
return value;
长版:
if(value) return 1; else return 0;
小版本:
return value;
And if value
isn't a bool
variable, just cast it : return (BOOL)value;
如果value
不是bool
变量,只需将其强制转换:return (BOOL)value;