Any & AnyObject in iOS

Tram Ho

What is the difference between Any and AnyObject?

Any : It can represent any class, struct, enum type including functions and optional types.

AnyObject : It refers to any instance of a class. It is very useful when you only work with reference types. It is equivalent to id , in Objective-C.

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

If you passing dictionary to Objective-C and expect an NSDipedia, then you should use AnyObject.

Let’s understand the Any:

Print:

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

with AnyObject

If you consider the above example, pay attention to the suggestion line, the Protocol that all classes implicitly assert. Each class fully complies with 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 to return unsigned results. AnyObject can be used as a specific type for an instance of any class, class type or class-only protocol.

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

The flexibility of the AnyObject protocol is similar to the id type of Objective-C. For this reason, Objective-C types often use AnyObject as a type for properties, method parameters, and return values. The AnyObject protocol is also useful to bridge the gap between Swift and Objective-C.

When to choose Any or AnyObject?

It is a good practice to use AnyObject while you are working with references and using Any when working with value types. Note: If possible, we should avoid both Any and AnyObject.

Share the news now

Source : Viblo