-
Notifications
You must be signed in to change notification settings - Fork 0
AnyObject
AnyObject is kind of a nightmare.
The documentation for AnyObject says:
The protocol to which all classes implicitly conform.
You might think that the sentence in the docs suggests that non-classes don't conform to AnyObject, and in Swift 1/2 that was the case, but (starting in Swift 3) that's not true at all. Objective-C's id
mapping was changed from AnyObject
(simple) to Any
(more lenient but more complex). In fact, on "Apple platforms" ({mac/i/tv/watch}OS -- and only these platforms), everything in Swift conforms to AnyObject.
Where is this documented? Not at all, AFAICT, except in the comments of SR-6715. They say it's working as intended. [XXX: they also say...]
WORKAROUND: In Swift 3 and up, then, how do you test if something is a reference type? As suggested in SR-6715:
type(of: x) is AnyObject.Type
Another submarine issue: suppose you have a field var x: Any?
, and you want to store a struct in it. Then you want to get the value out, and cast it to a protocol type, so you say x as? MyProtocol
.
It turns out that if the slot your storing it in was written in Objective-C (!!), this will be nil
.
(According to the comments of SR-3871, it sounds like this has something to do with bridging, but I'm not sure how that makes sense because Any
is for value types.)
WORKAROUND:
x as AnyObject as? MyProtocol