andrewz andrewz - 1 year ago 64
Swift Question

swift use of AnyClass object with as?

I would like to do this:

let myClass: AnyClass = functionReturningClass() // ex. String.self
if let myObject = functionReturningObject() as? myClass { ...

as? myClass
doesn't compile ('myClass is not a type'). What can I do?

Answer Source

Unfortunately this is not possible--as must know the type it is casting to at compile-time. You cannot provide a variable type to as. If you must cast, then you are limited to features like generics and overloading that work at compile-time.

Think about it--what methods should the compiler allow you to call on the resulting myObject? It's impossible to say without knowing the runtime value of myClass. It makes good sense, therefore, that this doesn't work.

You can still return subclasses from functionReturningObject(). You can still cast them to different types. You just can't decide what type to cast them to dynamically at runtime.