我需要实现此功能:
类
class Foo{
func method1()
}
class Bar{
static method2()
}
然后,在接收方法中:
func receiveClassType(type:AnyClass){
//check class type
//If class Foo, cast received object to Foo, instantiate it and call method1()
//If class Bar, cast received class to Bar call static method method2()
}
非常感谢。
答案 0 :(得分:1)
你有从Class类型实例化吗?由于Objective-C运行时的动态特性,这将在Objective C中起作用。但是你不能在Swift中实现。
也许考虑使用枚举...
enum Classes: String {
case foo, bar
func instantiate() -> Any {
var result: Any
switch self {
case .foo:
let foo = Foo()
foo.method1()
result = foo
case .bar:
let bar = Bar()
bar.method2()
result = bar
}
return result
}
}
func receiveClassType(type: String){
guard let aClass = Classes(rawValue: type) else { return }
aClass.instantiate()
}