有没有一种简便的方法可以快速解包和分配? [英] Is there a concise way to unwrap and assign in swift?

查看:57
本文介绍了有没有一种简便的方法可以快速解包和分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我迅速有一个丑陋(但有效)的未包装代码块:

I have an ugly (but working) chunk of unwrapping code in swift:

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

还有没有更简洁的方法可以像在C ++中一样迅速地编写此代码?

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

推荐答案

Swift具有零合并运算符" ??,它完全可以满足您的要求 正在寻找:

Swift has the "nil coalescing operator" ?? which does exactly what you are looking for:

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

其中,只有在a == nil时才评估b(短路评估).

where b is only evaluated if a == nil (short-circuit evaluation).

这篇关于有没有一种简便的方法可以快速解包和分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆