传递一个 Swift 类作为参数,然后从中调用一个类方法 [英] Pass a Swift class as parameter, and then call a class method out of it

查看:70
本文介绍了传递一个 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()

这篇关于传递一个 Swift 类作为参数,然后从中调用一个类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆