【发布时间】:2016-08-09 05:40:10
【问题描述】:
获取此代码:
protocol P: class {
static var hello: String { get }
}
class A: P {
class var hello: String {
return "Hello"
}
}
class B: A {
override static var hello: String {
return "Hello World"
}
}
class C: A {}
class D: C {
override static var hello: String {
return "Hello D"
}
}
func sayHello(elements: P.Type...) {
for p in elements {
print(p.hello)
}
}
func sayHelloAgain(elements: A.Type...) {
for p in elements {
print(p.hello)
}
}
func sayHelloThe3rd(elements: [A.Type]) {
for p in elements {
print(p.hello)
}
}
sayHello(A.self, B.self, C.self)
sayHelloAgain(A.self, B.self, C.self)
比较一下(取自presentation)
func register<T: UITableViewCell where T: ReusableView, T: NibLoadableView>(_: T.Type) { ... }
tableView.register(FoodTableViewCell)
为什么我必须在一种情况下使用 A.self,而在另一种情况下不用? 而且,使用一个参数调用时不需要使用 .self。
sayHello(A)
sayHello(A, B) //doesn't compile
【问题讨论】:
-
您引用的旧代码现在会生成一个警告,您应该添加
.self。在早期版本的 Swift 中,.self可能会被猜到,编译器会坚持使用它,但正如 Alexander 在下面所述,Swift 将始终需要它。
标签: swift