Jeff
Jeff

Reputation: 1800

Dynamic casting using result of NSClassFromString("MyUIViewController")

I'm finding that the following code does not work, but I don't exactly understand why.

Say I have a class name saved in a string. I want to cast a view controller as the class that this string refers to.

let controller = self.navigationController as! NSClassFromString("MyUIViewController")

Swift doesn't seem to understand this - I get this error:

Undeclared use of NSClassFromString.

Or the error:

Consecutive statements must be separated by `,`

Can anyone explain why this is the case? I can't cast (using as?) a type based on some variable?

Thanks

Upvotes: 0

Views: 817

Answers (1)

rob mayoff
rob mayoff

Reputation: 385600

No, you cannot cast to a runtime type object. You must cast to a compile-time type. This is why we write x as Int, not x as Int.self: Int is a type, and Int.self is an object that represents that type at runtime.

What would it mean to cast to NSClassFromString("MyUIViewController")? Now you have a variable, controller, whose value is some type that the compiler knows nothing about, so the compiler cannot let you do anything with controller. You can't call methods or access properties on it, because the compiler doesn't know what methods or properties it has. You can't pass it as an argument to a function, because the compiler doesn't know whether it is the right type for that argument.

If you edit your question to explain what you want to do with controller (what methods you want to call on it or what properties you want to access or what functions you want to pass it to), then I will revise my answer to address your goal.

Upvotes: 1

Related Questions