0
0
Swiftprogramming~5 mins

Any and AnyObject types in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AString
BAnyObject
CInt
DAny
Can AnyObject hold a value of type Int?
ANo, because Int is a value type
BYes, but only if Int is boxed
CYes, always
DOnly if Int conforms to a class
How do you safely convert a variable of type Any to String?
AUsing <code>as?</code>
BUsing <code>as!</code>
CUsing <code>is</code>
DUsing <code>cast()</code>
Which of these is true about Any and AnyObject?
A<code>AnyObject</code> can hold structs
B<code>AnyObject</code> can hold functions
C<code>Any</code> can hold class instances and value types
D<code>Any</code> can only hold class instances
Why might you avoid using Any in your Swift code?
AIt improves performance
BIt makes code less type-safe and harder to understand
CIt restricts to class types only
DIt automatically converts types
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.