使用前导点符号调用 Swift 类工厂方法? [英] Calling a Swift class factory method with leading dot notation?
问题描述
在最近的一个问题中,发布者有这行有趣的代码:
In a recent question, the poster had this interesting line of code:
self.view.backgroundColor = .whiteColor()
看到这个我很惊讶.我只见过用于枚举值的前导点符号.在这种情况下,backgroundColor
是 UIColor?
类型,whiteColor
是 UIColor
上的一个类方法,它返回一个 <代码>UIColor.
I was surprised to see this. I've only ever seen the leading dot notation used for enum values. In this case, backgroundColor
is of type UIColor?
and whiteColor
is a class method on UIColor
that returns a UIColor
.
为什么会这样?这是调用工厂方法的合法方式吗?
Why does this work? It this a legitimate way to call a factory method?
推荐答案
这个功能叫做隐式成员表达式"
隐式成员表达式是在类型推断可以确定隐含类型的上下文中访问类型成员的缩写方式,例如枚举用例或类方法.它具有以下形式:
An implicit member expression is an abbreviated way to access a member of a type, such as an enumeration case or a class method, in a context where type inference can determine the implied type. It has the following form:
.
会员名
但是,就目前而言,我建议您不在 Optional
或 ImplicitlyUnwrappedOptional
上下文中使用此功能.
But, as of right now, I advise you should not use this feature in Optional
or ImplicitlyUnwrappedOptional
context.
虽然这有效:
// 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)
编译器有一些错误.请参阅:swift 是否不允许在函数参数中进行初始化?
The compiler has some bugs. see: does swift not allow initialization in function parameters?
这篇关于使用前导点符号调用 Swift 类工厂方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!