在最近的一个问题中,海报上有这个有趣的代码:
self.view.backgroundColor = .whiteColor()
Run Code Online (Sandbox Code Playgroud)
我很惊讶地看到这一点.我只见过用于枚举值的前导点符号.在这种情况下,backgroundColor
是类型UIColor?
并且whiteColor
是一个UIColor
返回a 的类方法UIColor
.
为什么这样做?这是调用工厂方法的合法方式吗?
rin*_*aro 32
此功能称为" 隐式成员表达 "
隐式成员表达式是在类型推断可以确定隐含类型的上下文中访问类型成员(例如枚举大小写或类方法)的缩写方式.它具有以下形式:
.
member name
但是,截至目前,我劝你不要在使用此功能Optional
或ImplicitlyUnwrappedOptional
内容.
虽然这有效:
// store in Optional variable
let col: UIColor?
col = .redColor()
// pass to function
func f(arg:UIColor?) { println(arg) }
f(.redColor())
Run Code Online (Sandbox Code Playgroud)
这会使编译器崩溃:(
func f(arg:UIColor?, arg2:Int) { println(arg) }
// ^^^^^^^^^^ just added this.
f(.redColor(), 1)
Run Code Online (Sandbox Code Playgroud)
编译器有一些错误.看:swift不允许在函数参数中初始化吗?
Air*_*ity 10
看起来规则是:如果类型具有返回该类型的静态方法,则可以在已确定返回类型的情况下跳过类型的名称:
struct S {
static func staticmethod() -> S {
return S()
}
static var staticproperty: S {
return S()
}
}
let s1: S = .staticmethod()
let s2: S = .staticproperty
Run Code Online (Sandbox Code Playgroud)
我想知道这是故意的,还是Enums实现的副作用,鉴于这个特性,可能会被认为是这样的语法糖:
struct FakeEnum {
let raw: Int
static var FirstCase: FakeEnum { return FakeEnum(raw: 0) }
static var SecondCase: FakeEnum { return FakeEnum(raw: 1) }
}
let e: FakeEnum = .FirstCase
Run Code Online (Sandbox Code Playgroud)
我在文档中找不到任何内容。但是,我相信它的工作方式是Swift从中知道上下文中存在哪种类型self.view.backgroundColor
,因此直接以点开头的表达式应该是该类型的静态对象(静态方法或静态属性)。
以下工作很好:
struct Foo {
static func fooMethod() -> Foo {
return Foo()
}
static var fooProperty: Foo = Foo()
}
var foo: Foo
foo = .fooMethod()
foo = .fooProperty
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7717 次 |
最近记录: |