2016-03-08 39 views
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”。

我想知道:

  1. 这是为什么?
  2. 以及如何声明一个函数与多个参数不需要“.self”在哪里使用它?

回答

2

巧合的是,这只是迅速发展。在Type为唯一参数时省略.self的能力已在Swift中报告为bug

从苹果相关报价:

这是一个错误。应该到处都需要.self。 不幸的是,我们已经有了一段时间的bug,所以我不确定有多少 代码会因为改变而破坏。如果我们想要删除 要求,那么这将被视为语言更改,并且将有 经历Swift Evolution流程。

+0

哦,为什么这是一个错误?我希望它是一个功能。我问这个问题的原因是我想创建一个DSL take类作为参数,如布局(UIVIew,[ViewClass1,ViewClass2,..])。自己到处都不是很优雅。 – xfx