I'm currently studying swift by watch stanford ios tutorial series. The lecturer mentioned in the first class that we shouldn't use AnyObject. I was just wondering what is the reason behind it? Is it a bad coding practice? or is it because of some other reasons? Thanks in advance for any help!
AnyObject
means any kind of class (or reference type) it is similar to id
in objective-C. It is a protocol to which all classes implicitly conform.
The problem is that the compiler doesn't know which kind of object it is at compile time, this means that you can easily build an app that sends methods to a wrong object.
This usually trigger this kind of exception on NSObject
subclasses "unrecognized selector sent to instance XXXXXX
"with a crash.
Swift likes strong typing, this is really helpful because you can fix problems before they happen, but if you define an object as AnyObject
it can be everything.