Any VS AnyObject ? Swift

Swift provides two typealiases for working with non specific types. In simple words we can say.

AnyObject

it can represent an instance of any class type.

Any

it can represent an instance of any type at all, including function types.

But here i want to mention that Apple warns to use Any and AnyObject only when you explicity need the behaviour because it always good to be more specific about the types what you are expecting in your code.

class MyClass   {   }

var things = [Any]()
things.append("String")
things.append(9)
things.append(2.0)
things.append(MyClass())

This things arrays contains IntString, Double and Class as well. Complier convert the Objective C id type into AnyObject since they are class type. Now to discover the specific type of constant and variable, we can use is or as pattern in switch statement cases.

for thing in things {
    switch thing {
        case let someInt as Int:
        print("Some Int Value is there \(someInt)")

    case let someString as String:
        print("Some String Value is there \(someString)")

    case let someFloat as Double:
        print("Some Double Value is there \(someFloat)")
      
    case let someClass as MyClass:
        print("MyClass Class is there")

    default:
        print("Unknown")
    }
}

So summary is Any type represents value of any type including optional types but complier will give you the warning if you really want to use than use as optional value as an Any value.

things.append(optionalNumber as Any)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s