AnyObject vs Any vs NSObject vs id — the difference
Four levels of "anything"
Any— any Swift type: struct, enum, class, function,Optional, tuple. An existential container; to do anything you needas?.AnyObject— any class instance (reference type). A class-bound protocol; used forweakreferences to "something", for identity===, in generic constraintsT: AnyObject. On Apple platformsAnyObjectsupports@objccalls through the optional syntax:obj.perform(...),(obj as AnyObject).description.AnyClass—AnyObject.Type, "any class as a value" (a metatype):let cls: AnyClass = UIView.self,NSClassFromString.NSObject— the concrete root class of Foundation. Providesisa, KVC/KVO,isEqual/hash,description,NSCoding,#selector, compatibility with Cocoa APIs. Not to be confused with the protocolNSObjectProtocol(NSObjectin Obj-C), which describes the same contract forNSProxyandAnyObjectexistentials.id(Obj-C) — a pointer to any Obj-C object. Imported into Swift asAny, notAnyObject(SE-0116, Swift 3): anidcan hold aString,Int, array — Swift bridges them toNSString,NSNumber,NSArrayautomatically, so the only honest type isAny.
import Foundation
final class Box: NSObject {
@objc dynamic var value = 1
}
let anything: [Any] = [1, "two", Box(), { (x: Int) in x }]
let objects: [AnyObject] = [Box(), NSString(string: "s")]
let cls: AnyClass = Box.self
let legacy: Any = NSNumber(value: 3) // this is how id arrives from Obj-C
func describe(_ v: Any) -> String {
switch v {
case let n as Int: return "Int \(n)"
case let s as String: return "String \(s)"
case let o as NSObject: return "NSObject \(o)"
default: return "other"
}
}
print(describe(legacy)) // Int 3 — NSNumber bridges to Int
_ = (anything, objects, cls)
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep