简体   繁体   中英

Pass a class type as a parameter and create instance of it afterwards

I need to achieve this feature:

  • Pass a class type as a parameter
  • Check class type
  • If I need to call an instance method, instantiate it and call function
  • Or call static class method

Classes

class Foo{
    func method1()
}

class Bar{
    static method2()
}

Then, in the receiving method:

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

}

Many thanks.

Do you have to instantiate from a Class type? This would work in Objective C due thanks to the dynamic features of the Objective-C runtime. but isn't something you can achieve in Swift.

Maybe consider using an enum…

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM