Swift:使用NSClassFromString使用所需的初始化参数实例化类?

时间:2019-03-25 16:53:13

标签: swift class instantiation

我正在尝试重构一些具有重复性的代码。我将/如何动态实例化构造函数参数中传递的item_class

let items = [
    ["name": "cards", "class": "SG_Card"],
    ["name": "contacts", "class": "SG_Contact"],
]

func getStuff(params:[String:String]){
    let item_name = params["name"]!
    let item_class_name = params["class"]!

    // how would I set item_class's type
    // item_class:item_class_name does not work
    let item_class = NSClassFromString(item_class_name)
    // let card = item_class(data: json) 
}

for item in items {
    getStuff(params: item)
}

0 个答案:

没有答案