基于Swift中作为参数传递的Class实现动态初始化

时间:2014-07-07 12:13:56

标签: ios swift

我想根据传递给函数的类创建对象。

首先,我有一个接口,每个可生成的对象应符合:

interface Generatable{

    init(raw: NSDictionary)

}

以及将该类作为参数的函数

func generateDynamicObjectFromClass(generatable: Generatable.Type){

    var someJSONData : NSDictionary = NSDictionary()
    var myGeneratedObject : Generatable = generatable(raw: someJSONData) //custom initialiser of Generatable class

}

然后,就这样称呼它:

generateDynamicObjectFromClass(MyGeneratableObject.Type)

MyGeneratableObject类

class MyGeneratableObject : NSObject, Generatable{

    init(raw: NSDictionary){
         //some initialisation
    }

}

但是,MyGeneratableObject没有Type属性,因此问题是在运行时获取底层对象的相应类。那可能吗 ?

1 个答案:

答案 0 :(得分:4)

您必须将generateDynamicObjectFromClass定义为通用函数:

protocol Generatable {
    init(raw: NSDictionary)
}

func generateDynamicObjectFromClass<T where T:Generatable>(generatable:T.Type, otherParam: NSString = "") -> T {
    var someJSONData : NSDictionary = NSDictionary()
    var myGeneratedObject = T(raw: someJSONData)
    return myGeneratedObject
}

class MyGeneratableObject : NSObject, Generatable {

    init(raw: NSDictionary){
        println("MyGeneratableObject init")
    }
}

var myObject1  = generateDynamicObjectFromClass(MyGeneratableObject.self, otherParam: "foo")
var myObject2  = generateDynamicObjectFromClass(MyGeneratableObject.self)

或者,您可以将对象创建为

var myObject = MyGeneratableObject(raw: NSDictionary())

无需单独的功能。