The problem here is that you think of Bus as a specific thing. This is really not the case. Bus<String> is. Bus<Int> too. But Bus not, at least, not in the same sense. You need to know what T .
Indeed, you want to write something like this:
func checkType<T>(object: AnyObject) { if let foo = object as? Bus<T> { println("Bus<T>") } }
But if you try to use it, you will get an error message:
// error: Argument for generic parameter 'T' could not be inferred. checkType(myBus)
Unlike other languages, you cannot write checkType<String>(myBus) . But the following can do what you are looking for:
func checkType<T>(object: AnyObject, T.Type) { if let foo = object as? Bus<T> { println("Bus<T>") } } checkType(myBus,String.self)
This fixes that T for any Bus<T> and will work correctly.
You may object that you do not want to indicate what T . However, instead, this leads to the question ... as soon as you find out that object is a kind of Bus , what are you going to do? Are you planning on calling methods on it or passing it as an argument to other functions? Most likely, what you are trying to achieve can be better done with a common function and protocol restrictions, instead of using AnyObject and casting.
source share