andrewz andrewz - 4 months ago 11
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 { ...


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

Answer

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.

Comments