【问题标题】:Is there a concise way to unwrap and assign in swift?有没有一种简洁的方法可以快速展开和分配?
【发布时间】:2014-10-04 00:52:59
【问题描述】:

我在 swift 中有一段丑陋(但有效)的解包代码:

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

有没有更简洁的方法可以像我在 C++ 中那样用 swift 编写?

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

【问题讨论】:

    标签: memory swift


    【解决方案1】:

    Swift 有“nil 合并运算符”??,它完全符合您的要求 正在寻找:

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

    documentation 中所述,a ?? b

    a != nil ? a! : b
    

    其中b 仅在a == nil 时才被评估(短路评估)。

    【讨论】:

    • 太棒了!我错过了阅读文档。很方便知道。
    • @0O0O0O0: ?? 仅在 Xcode 6 beta 5 中引入,因此很容易错过。
    猜你喜欢
    • 2021-11-11
    • 2016-03-30
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    相关资源
    最近更新 更多