我写了一些函数(Swift 2.1,XCode 7.1.1):
public func test1<T:UIView>(type: T.Type) -> T {
print(type.dynamicType)
return type.init()
}
public func test2<T:UIView>(type: T.Type)(_ n: Int) -> T {
print(type.dynamicType)
return type.init()
}
public func test3<T1:UIView, T2:UIView>(type1: T1.Type, _ type2: T2.Type) {
print(type1.init())
print(type2.init())
}
public func test4<T:UIView>(type: T.Type, _ n: Int) {
print(type.init())
print(n)
}
public func test5<T:UIView>(n: Int,_ type: T.Type) {
print(type.init())
print(n)
}
用以下方式打电话给他们:
test1(UIButton)
test1(UIButton.self)
test2(UIButton)(1)
test2(UIButton.self)(1)
test3(UIButton.self, UITextField.self)
test4(UIButton.self, 1)
test5(1, UIButton.self)
如您所见,当一个类型是唯一的参数时,它可以省略“.self”。但对于所有不具有类型参数的函数,它们都需要“.self”。
我想知道:
答案 0 :(得分:2)
巧合的是,这只是出现了快速进化。当Type是唯一的参数时,忽略.self
的能力在Swift中被报告为bug。
Apple的相关引言:
这是一个错误。应该到处都需要
.self
。 不幸的是,我们已经有一段时间了,所以我不知道有多少 代码我们通过改变来打破。如果我们想删除 要求,这将被视为语言变化,并将有 通过斯威夫特进化过程。