by helsy infotech    2 years ago

Introduction

Swift has two anonymous types “Any” and “AnyObject”.

Any can represent any type at all including function type and optional type.

AnyObject can represent any class type.

Swift provides two nonspecific types called any and anyobject.

Any OBJECT

AnyObject is used for class types.

The protocol to which all classes implicitly conform.

Declaration

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.

  • let A : AnyObject = myRef.self

AnyObject can also be used the concrete type for a type that bridges to an Objective-C class. Many value types in Swift bridge to Objective-C, like string and int.

  • let a : AnyObject = "This is AnyObject" as NSString
  • let b: AnyObject = 10 as NSNumber
  • E.g. - AnyObject Array
  • Var anyObjArray : [AnyObject] = [1 as AnyObject, 2 as AnyObject, “ios” as AnyObject]

Any

Any is used for all types. Any allowed to work with a mix of different types including function and non-class types such as int, string, and bool. According to the elements in this array are structs are value types, so in theory, AnyObject should not work in these cases.

Declaration

Any is used for all types. Any allowed to work with a mix of different types including function and non-class types such as int, string, and bool. According to the elements in this array are structs are value types, so in theory, AnyObject should not work in these cases.

Declaration

Let’s make a quick comparison. Consider that a constantly called age has value 20 and is of type Int.

  • E.g. Let age : Any = 20
  • Output :- 20

This type Int is specific - we are very clear here about the fact that age is an integer number.

Now let’s check out a nonspecific type that uses Any. The following code defines a values array of type [Any] :

  • E.g. - Any Array
  • let values:[Any] = [“ios”,25,”Programming”,-1]
  • Output :- [“ios”,25,”Programming”,-1]