传递一个Swift类作为参数,然后调用一个类方法

我希望能够将一个类作为variables存储,所以我可以稍后调用类方法,如下所示:

class SomeGenericItem: NSObject { var cellClass: AnyClass init(cellClass: AnyClass) { self.cellClass = cellClass } func doSomething(p1: String, p2: String, p3: String) { self.cellClass.doSomething(p1, p2: p2, p3: p3) } } class SomeClass: NSObject { class func doSomething(p1: String, p2: String, p3: String) { ... } } 

我想能够像这样说:

 let someGenericItem = SomeGenericItem(cellClass: SomeClass.self) someGenericItem.doSomething("One", p2: "Two", p3: "Three") 

我想弄明白的是:

1)如何定义一个协议,以便我可以调用类func doSomething?
2)cellClass的声明需要什么?
3)电话会是什么样子?

协议不能定义类方法,但静态方法是好的。 你将需要你的包装是通用的,并指定一个“where”约束来保证包装types符合你的协议。

例:

 protocol FooProtocol { static func bar() -> Void } class FooishClass : FooProtocol { static func bar() -> Void { println( "FooishClass implements FooProtocol" ) } } class FooTypeWrapper< T where T: FooProtocol > { init( type: T.Type ) { //no need to store type: it simply is T } func doBar() -> Void { T.bar() } } 

使用:

 let fooishTypeWrapper = FooTypeWrapper( type: FooishClass.self ) fooishTypeWrapper.doBar()