class MyClass {} let anyVar: Any = MyClass() let anyObjectVar: AnyObject = MyClass() print(type(of: anyVar)) print(type(of: anyObjectVar))
The variable anyVar is of type Any but holds an instance of MyClass. The type(of:) function returns the actual runtime type, so it prints MyClass. Similarly, anyObjectVar is of type AnyObject and holds MyClass instance, so it also prints MyClass.
Any and AnyObject in Swift?Any can hold any type: classes, structs, enums, and basic types. AnyObject is limited to class instances only, which are reference types.
The integer literal 5 is a value type (Int). AnyObject can only hold references to class instances. So assigning 5 to AnyObject causes a compile error.
let anyVar: Any = MyClass(), which option safely casts anyVar to MyClass?The as? operator attempts a safe cast and returns an optional. The if let unwraps it safely. as without question mark is for upcasting or forced cast. is returns a Bool, not a cast. as! is forced cast but the syntax in option D is invalid.
Any can hold any type including value types like Int and String, and class instances. AnyObject can only hold class instances, so option C cannot hold 42 or "Hello". Option C is valid but only holds class instances, so it doesn't hold value types.