1
我已经写了一些功能(SWIFT 2.1时,Xcode 7.1.1):迅速类作为参数,而.self
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”。
我想知道:
- 这是为什么?
- 以及如何声明一个函数与多个参数不需要“.self”在哪里使用它?
哦,为什么这是一个错误?我希望它是一个功能。我问这个问题的原因是我想创建一个DSL take类作为参数,如布局(UIVIew,[ViewClass1,ViewClass2,..])。自己到处都不是很优雅。 – xfx