这行代码是什么意思?
label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;
的吗?还有,迷惑我吧。
这行代码是什么意思?
label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;
的吗?还有,迷惑我吧。
当前回答
基于Barry Wark的精彩解释……
三元操作符的重要之处在于它可以用于if-else不能使用的地方。即:在条件或方法参数内。
[NSString stringWithFormat: @"Status: %@", (statusBool ? @"Approved" : @"Rejected")]
...这是预处理常量的一个很好的用途:
// in your pch file...
#define statusString (statusBool ? @"Approved" : @"Rejected")
// in your m file...
[NSString stringWithFormat: @"Status: %@", statusString]
这使您不必在if-else模式中使用和释放局部变量。增值!
其他回答
它是三元或条件运算符。它的基本形式是:
condition ? valueIfTrue : valueIfFalse
其中只有在选中值时才会计算值。
这只是if-then-else语句的一种简短形式。它的意思与下面的代码相同:
if(inPseudoEditMode)
label.frame = kLabelIndentedRect;
else
label.frame = kLabelRect;
我刚学了一些关于三元运算符的新东西。省略中间操作数的简短形式确实很优雅,这是C语言仍然重要的众多原因之一。仅供参考,我第一次真正了解这个是在c#实现的一个例程的上下文中,该例程也支持三元操作符。由于三元运算符是在C语言中,因此在其他本质上是它的扩展的语言中(例如,Objective-C, c#)也是如此。
基于Barry Wark的精彩解释……
三元操作符的重要之处在于它可以用于if-else不能使用的地方。即:在条件或方法参数内。
[NSString stringWithFormat: @"Status: %@", (statusBool ? @"Approved" : @"Rejected")]
...这是预处理常量的一个很好的用途:
// in your pch file...
#define statusString (statusBool ? @"Approved" : @"Rejected")
// in your m file...
[NSString stringWithFormat: @"Status: %@", statusString]
这使您不必在if-else模式中使用和释放局部变量。增值!
正如大家所说,它是一种表示条件运算符的方法
if (condition){
true
}
else {
false
}
使用三元运算符(条件)?真:假 为了增加额外的信息,在swift中我们有新的方法来表示它使用??
let imageObject: UIImage = (UIImage(named: "ImageName")) ?? (initialOfUsername.capitalizedString).imageFromString
这和
int a = 6, c= 5;
if (a > c)
{
a is greater
} else {
c is greater
}
等于
如果(> c) ?a:c ==> = if (a>c)?c:
我们可以用??是迅速的。