[英]Ternary operator with nothing in 'if' condition
以下代碼做什么?
return obj ? : [NSNull null];
根據我對三元運算的理解,它相當於:
if (!obj)
return [NSNull null];
但是if (obj)
返回什么? 是否仍然return [NSNull null]
?
如果obj
為True
,則返回obj
。
return obj ? : [NSNull null];
等效於:
id x = obj;
if (x) {
return x;
else {
return [NSNull null];
}
只要obj沒有副作用,它在邏輯上就等同於:
return obj ? obj : [NSNull null]
編碼...
return foo ? : bar;
將返回與...相同的值
return foo ? foo : bar;
不同之處在於,第一種方法只檢查一次foo
值。
最好在某些情況下使用第一個。
例如,創建一個對象...
// this would create two objects, one to check and the other to return
return [MyObject objectWithSomeParam:param] ? [MyObject objectWithSomeParam:param] : bar;
或運行昂貴的功能...
// the expensive function here is run twice
return [self someExpensiveFunction] ? [self someExpensiveFunction] : bar;
這兩個都將從使用中受益
return foo ?: bar;
本質上,如果驗證對象與返回對象的true相同,則使用縮短的版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.