2014-10-03 50 views
2

我有迅速展开代码的一个丑陋的(但工作)块:是否有一种简洁的方式来快速打开和分配?

var color = UIColor.whiteColor() 
if (label.backgroundColor? != nil) 
{ 
    color = label.backgroundColor! 
} 

是否有迅速像我将会用C++做写任何更简洁的方式?

UIColor color = (label.backgroundColor==nil) ? 
    UIColor.whiteColor() : label.backgroundColor; 

回答

10

斯威夫特有 “无合并运算符” ??它做了你 正在寻找什么:

let color = label.backgroundColor ?? UIColor.whiteColor() 

正如documentation指出,a ?? b

a != nil ? a! : b 
快捷方式

其中b仅在a == nil(short-ci电路评估)。

+0

太棒了!我错过了通过文档阅读。非常方便知道。 – Ideasthete 2014-10-03 16:52:55

+0

@ 0O0O0O0:'''只在Xcode 6 beta 5中引入,所以很容易错过。 – 2014-10-03 16:59:52

相关问题