Recall & Review
beginner
What does the
Any type represent in Swift?Any can represent an instance of any type at all, including function types and optional types.
Click to reveal answer
beginner
What is the difference between
Any and AnyObject in Swift?<p><code>Any</code> can hold any type, including value types like <code>Int</code> or <code>Struct</code>. <code>AnyObject</code> can only hold instances of class types (reference types).</p>Click to reveal answer
beginner
Can
AnyObject hold a struct or enum instance?<p>No, <code>AnyObject</code> can only hold class instances. Structs and enums are value types and cannot be stored in <code>AnyObject</code>.</p>Click to reveal answer
intermediate
How do you cast a variable of type
Any to a specific type in Swift?<p>You use optional casting with <code>as?</code> or forced casting with <code>as!</code>. For example: <code>let number = anyVar as? Int</code>.</p>Click to reveal answer
intermediate
Why would you use
Any or AnyObject in your Swift code?<p>Use <code>Any</code> when you need to store or work with values of different types in a single collection or variable. Use <code>AnyObject</code> when you want to restrict to class instances only.</p>Click to reveal answer
Which Swift type can hold any kind of value, including functions and optionals?
✗ Incorrect
Any can hold any type, including functions and optionals. AnyObject is limited to class instances.
Can
AnyObject hold a value of type Int?✗ Incorrect
AnyObject can only hold class instances. Int is a value type and cannot be stored in AnyObject.
How do you safely convert a variable of type
Any to String?✗ Incorrect
Use optional casting as? to safely convert Any to String. Forced casting as! can crash if the type is wrong.
Which of these is true about
Any and AnyObject?✗ Incorrect
Any can hold any type including value types and class instances. AnyObject is limited to class instances.
Why might you avoid using
Any in your Swift code?✗ Incorrect
Using Any reduces type safety and can make code harder to read and maintain.
Explain the difference between
Any and AnyObject in Swift and give an example of when to use each.Think about value types vs reference types.
You got /3 concepts.
Describe how to safely cast a variable of type
Any to a specific type and why forced casting can be risky.Consider optional vs forced casting.
You got /3 concepts.