将类类型作为参数传递,然后创建它的实例

时间:2017-03-19 11:13:26

标签: ios swift

我需要实现此功能:

  • 将类类型作为参数传递
  • 检查班级类型
  • 如果我需要调用实例方法,请实例化它并调用函数
  • 或者调用静态类方法

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()

}

非常感谢。

1 个答案:

答案 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()

}