0

I am wanting to convert a string into a class type.

func getViewController(sbName: String, vcName: String, vcType: String) -> UIViewController{
    let classType = ????? //What to put here?
    let sb = UIStoryboard(name: sbName, bundle: nil)
    var vc = sb.instantiateViewControllerWithIdentifier(vcName) as classType

    return vc 
}

If anyone could lead me in the right direction, I'd greatly appreciate it! I have a feeling there is a way to do it but have not been able to find a way how.

1 Answer 1

2

If you are only worried about Objective-C based classes, you can use NSClassFromString("ClassName")

However, your method is returning UIViewController explicitly. Casting vc to the class type is not going to help you at all.

Perhaps a generic method would be better for you:

func getViewController<T: UIViewController>(sbName: String, vcName: String) -> T {
    let sb = UIStoryboard(name: sbName, bundle: nil)
    var vc = sb.instantiateViewControllerWithIdentifier(vcName) as T
    return vc
}

The type can then be inferred from the variable you are trying to assign this to:

var viewController: MyViewController = getViewController("ASDF", "ASDF")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this fixed my issue too. Your answer should be accepted!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.