1. Any: Can represent Any type, even method type (func)
  2. AnyObject: represents an instance object of any class type (similar to id in OC)
  3. AnyClass: represents the metatype of AnyClass. The type of any class implicitly obeys this protocol. AnyObject. The Type. If you have a Student class, Student.Type is the meta Type of Student.
// AnyObject: protocol AnyObject {}Copy the code

In particular, all classes implicitly implement this interface, which is why AnyObject is only suitable for class types. In Swift, all the basic types, including Array and Dictionary, which are traditionally classes, are struct types and cannot be represented by AnyObject. Therefore, Apple proposed a more special Any. In addition to class, it can represent all types, including struct and enum.

And just to understand that, here’s an interesting example. To test Any and AnyObject features, write the following code in Playground:

import UIKit

let swiftInt: Int = 1
let swiftString: String = "miao"

var array: [AnyObject] = []
array.append(swiftInt)
array.append(swiftString)
Copy the code

Here we declare an Int and a String, both of which should be represented only by Any, not by AnyObject. But you’ll find that this code will compile and run. Does that mean Apple’s programming guide is wrong? No, you can print array, and you’ll see that the elements are actually nsNumbers and NSStrings, and there’s an automatic conversion going on. Since we import UIKit (actually all we need here is Foundation, and we import Foundation at the same time when we import UIKit), the corresponding types in Swift and Cocoa are automatically converted. Because we explicitly declared that we needed AnyObject, the compiler thought we needed Cocoa types instead of native types, and did the automatic conversion for us.

In the above code, if we had removed the import UIKit, we would have gotten a compilation error that was not compatible with AnyObject. All we need to do is change the array declaration from [AnyObject] to [Any], and we’ll be all right.

let swiftInt: Int = 1
let swiftString: String = "miao"

var array: [Any] = []
array.append(swiftInt)
array.append(swiftString)
array
Copy the code

By the way, it helps to use only Swift types instead of Cocoa types, so we should use native types wherever possible.