Search code examples
swifttypesnsobjectanyanyobject

When is a variable a AnyObject but not a NSObject


Imagine a variable declared as below:

let sample : AnyObject = "anyobject" as AnyObject

Now when I try to retrieve the type of the var sample, it shows as NSObject.

Following is the code snippet:

   let sample : AnyObject = "anyobject" as AnyObject

        if sample is NSObject {
            print("Type is NSObject")
        }

        if sample is AnyObject {
            print("Type is AnyObject")
        }

        if sample is Any {
            print("Type is Any")
        }

And the output is:

Type is NSObject
Type is AnyObject
Type is Any

I thought the output would be AnyObject and Any since AnyObject is a subset of Any. But it did show NSObject as well.

My Question is:
1. When is a variable a AnyObject but not a NSObject?
2. When is a variable type Any but not NSObject?

As per my understanding,

NSObject is a subset of AnyObject. NSObject is the base class for most ObjC objects.
AnyObject is a subset of Any. AnyObject is an instance of any class type.
Any is a representation of an instance of any type at all, including function types and optional types.

Please correct me if I am wrong with the above understanding.
Sorry I am kind of new to Objc and need help in understanding the concepts. Any website url which explains these concepts would be useful. Thanks in Advance! :)


Solution

  • On platforms with Objective-C compatibility (which means all of Apple's platforms and no others), every class type is (secretly) a subclass of the SwiftObject class, which provides NSObject protocol conformance.

    On other platforms, NSObject is “just another class”, implemented in Swift, so only a class that explicitly has NSObject as a superclass has instances that are NSObjects.