roof
roof

Reputation: 450

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

I need to achieve this feature:

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.

Upvotes: 0

Views: 155

Answers (1)

Ashley Mills
Ashley Mills

Reputation: 53231

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

}

Upvotes: 1

Related Questions