有没有办法通过使用包含类名称的变量来初始化swift中的类?

时间:2017-04-11 04:06:28

标签: swift

假设我有一个简单的工厂,它返回自定义ModelObject类的各个子类,如:

class func testModelObject(className: String) -> ModelObject
{
   let obj = // instance of the subclass of ModelObject specified by className
   return obj
}

有办法做到这一点吗?当我试图调用该对象的任何方法时,Swift会不会感到害怕?我的退货类型应该还有别的吗?

1 个答案:

答案 0 :(得分:1)

为了获得最佳的类型安全性,您应该让testModalObject接受类似以下的元类型:

class ModelObject {
    required init() {}
}

class Subclass: ModelObject {
    required init() { super.init() }
}

func testModalObject(_ type: ModelObject.Type) -> ModelObject {
    return type.init()
}

testModalObject(Subclass.self)

如果您确实需要字符串输入,则需要依赖Objective-C运行时并进行一些转换(请参阅how to create instance of a class from a string in swift 3):

@objc
class ModelObject: NSObject {     // <---
    required override init() {}
}

@objc(MOSubclass)    // <-- tell ObjC the name is "MOSubclass" instead of "????.Subclass".
class Subclass: ModelObject {
    required init() { super.init() }
}

func testModalObject(_ typeName: String) -> ModelObject? {
    let cls = NSClassFromString("MO\(typeName)") as? ModelObject.Type
    return cls?.init()
}

testModalObject("Subclass")!