将 swift Class 传递给泛型函数
Passing a swift Class to Generic Function
我正在尝试使用泛型动态创建一个 class 基于实例的类型,但是我遇到了一些奇怪的行为。在示例 1 中,一切正常,但在示例 2 中,如果我将 Test.self 传递给通用函数,则它不起作用。类型一样,一切都一样,我不明白为什么。
class Test{
required init(x: Int){
// Do Something
}
}
class Builder{
init(){
}
func use<T>(test2: T.Type) -> Void{
test2(x: 10) // Error: T cannot be constructed because it has no accessible initializers
}
}
// Example 1:
let test1 = Test.self
test1(x: 10)
// Example 2:
let builder = Builder()
builder.use(Test.self)
因为T
不是类型Test
。要解决此问题:
class Builder{
init(){
}
// T has to be of type Test or is a subclass of Test
func use<T: Test>(test2: T.Type) -> Void{
test2(x: 10)
}
}
当您定义 use<T>
函数时,您必须以某种方式告诉它您传递的 class 将有一个 init(x:)
构造函数。
您可以通过声明协议并使可选类型 T
符合该协议来做到这一点。
试试这个:
protocol TestProtocol {
init(x:Int)
}
class Test: TestProtocol {
required init(x: Int){
// Do Something
}
}
class Builder{
init(){
}
func use<T: TestProtocol>(test2: T.Type) -> TestProtocol {
return test2(x: 10)
}
}
PD:在 Swift 1.2
上测试
我正在尝试使用泛型动态创建一个 class 基于实例的类型,但是我遇到了一些奇怪的行为。在示例 1 中,一切正常,但在示例 2 中,如果我将 Test.self 传递给通用函数,则它不起作用。类型一样,一切都一样,我不明白为什么。
class Test{
required init(x: Int){
// Do Something
}
}
class Builder{
init(){
}
func use<T>(test2: T.Type) -> Void{
test2(x: 10) // Error: T cannot be constructed because it has no accessible initializers
}
}
// Example 1:
let test1 = Test.self
test1(x: 10)
// Example 2:
let builder = Builder()
builder.use(Test.self)
因为T
不是类型Test
。要解决此问题:
class Builder{
init(){
}
// T has to be of type Test or is a subclass of Test
func use<T: Test>(test2: T.Type) -> Void{
test2(x: 10)
}
}
当您定义 use<T>
函数时,您必须以某种方式告诉它您传递的 class 将有一个 init(x:)
构造函数。
您可以通过声明协议并使可选类型 T
符合该协议来做到这一点。
试试这个:
protocol TestProtocol {
init(x:Int)
}
class Test: TestProtocol {
required init(x: Int){
// Do Something
}
}
class Builder{
init(){
}
func use<T: TestProtocol>(test2: T.Type) -> TestProtocol {
return test2(x: 10)
}
}
PD:在 Swift 1.2
上测试