假设我有一个简单的工厂,它返回自定义ModelObject
类的各个子类,如:
class func testModelObject(className: String) -> ModelObject
{
let obj = // instance of the subclass of ModelObject specified by className
return obj
}
有办法做到这一点吗?当我试图调用该对象的任何方法时,Swift会不会感到害怕?我的退货类型应该还有别的吗?
答案 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")!