DevPrep

All topics › Objective-C

AnyObject vs Any vs NSObject vs id — the difference

Middle PRO

Four levels of "anything"

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

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store