小编典典

用前导点符号调用Swift类工厂方法?

swift

在最近的问题中,发布者具有以下有趣的代码行:

self.view.backgroundColor = .whiteColor()

看到这一点我感到很惊讶。我只看过用于枚举值的 前导点
符号。在这种情况下,backgroundColoris是type,UIColor?并且whiteColorUIColor返回的class方法UIColor

为什么这样做?这是调用工厂方法的合法方法吗?


阅读 315

收藏
2020-07-07

共1个答案

小编典典

功能 称为“
隐式成员表达式

隐式成员表达式是在类型推断可以确定隐式类型的上下文中访问类型成员(例如枚举用例 或类方法 )的缩写方式。它具有以下形式:

.``member name


但是,截至目前,我劝你 不要 在使用此功能OptionalImplicitlyUnwrappedOptional内容。

尽管这可行:

// store in Optional variable
let col: UIColor?
col = .redColor()

// pass to function
func f(arg:UIColor?) { println(arg) }
f(.redColor())

这会使编译器崩溃:(

func f(arg:UIColor?, arg2:Int) { println(arg) }
//                 ^^^^^^^^^^ just added this.
f(.redColor(), 1)
2020-07-07