Book Image

Application Development with Swift

By : Hossam Ghareeb
Book Image

Application Development with Swift

By: Hossam Ghareeb

Overview of this book

Table of Contents (14 chapters)

Using Any and AnyObject


According to our explanation in the previous section about type casting and type checking, Swift provides us with two general types to use if you don't want to specifically type the objects:

  • AnyObject: This type is used to represent instances of class types only and its equivalent to id in Objective-C

  • Any: This type is used to represent instances of any type like tuples, closures, and so on

These types are very useful, especially when you try to deal with Cocoa APIs, because, most of the time, you will receive an array of type AnyObject. As we know, Objective-C doesn't support a typed array. In these situations, you have to use the is, as, and as? operators of type casting and type checking to help you deal with Any and AnyObject types.

Let's see an example of using AnyObject:

var anyObjects = ["Str", 5, true, UILabel(), NSDateFormatter()]
anyObjects.append(11.5)
anyObjects.append([1, 2])

As we have seen in this strange array, it holds String, UILabel, and NSDateFormatter...