传递一个 Swift 类作为参数,然后从中调用一个类方法
问题描述:
我希望能够将一个类存储为一个变量,以便稍后我可以从中调用类方法,如下所示:
I want to be able to store a class as a variable, so I can call class methods out of it later, something like this:
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) 电话会是什么样子?
1) How would a protocol be defined so I could call class func doSomething?
2) What would the declaration of cellClass need to be?
3) What would the call look like?
答
协议不能定义类方法,但静态方法可以.您将需要您的包装器是通用的,并指定一个where"约束,以保证包装的类型符合您的协议.
Protocols can't define class methods, but static methods are fine. You'll need your wrapper to be generic, and specify a 'where' constraint that guarantees the wrapped type's conformance to your protocol.
示例:
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()