Any & AnyObject in iOS

We work around with instance or type every time when we code. In the case of non-specific type, we select Any or AnyObject.

Nitin Aggarwal
3 min readJan 20, 2020
Thanks to lukaszadam and undraw for these illustrations :)

What is the difference between Any and AnyObject?

Any: It can represent any type of class, struct, enum including function and optional types or you can say anything at all.

AnyObject: It refers to any instance of a class. It’s useful when you are working with reference type only. It’s equivalent to ‘id’ in Objective-C.

If your dictionary will be used only within Swift code, then you should use Any because your types (Int, Double, Float, String, Array, and Dictionary) are not objects.

If you will be passing your dictionary to Objective-C routines that expect an NSDictionary, then you should use AnyObject.

Let’s understand the Any:

Here is an example of Any in Swift. In this example, we are checking the type of all values using the type-checking ‘is’ keyword.

Let’s go with AnyObject:

If you will look into the above example, notice the suggestion line “The protocol to which all classes implicitly confirm.”. Every class implicitly conforms to the AnyObject protocol.

You use AnyObject when you need the flexibility of an untyped object or when you use bridged Objective-C methods and properties that return an untyped result. AnyObject can be used as the concrete type for an instance of any class, class type, or class-only protocol.

In the above example, you can see we can’t use Int or String or any other type as AnyObject.

The flexible behavior of the AnyObject protocol is similar to Objective-C's id type. For this reason, imported Objective-C types frequently use AnyObject as the type for properties, method parameters, and return values.

The AnyObject protocol is also useful to bridge the gap between Swift and Objective-C.

When should we choose Any or AnyObject?

It’s a good practice to use AnyObject while you are working with references and use Any when working with value types.

Note: If possible, we should avoid both Any and AnyObject. It’s better to be specific.

Have you any queries? comment on it.

Have you found it useful? clap it 👏🏻

--

--

Nitin Aggarwal

Lead iOS Engineer, Mentor, Author, Writer; 📙 Released "iOS Interview Handbook" 🔗 topmate.io/nitinagam17/827990