0
0
Swiftprogramming~20 mins

Any and AnyObject types in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Any and AnyObject Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of Any and AnyObject assignment
What is the output of this Swift code snippet?
Swift
class MyClass {}

let anyVar: Any = MyClass()
let anyObjectVar: AnyObject = MyClass()

print(type(of: anyVar))
print(type(of: anyObjectVar))
A
MyClass
MyClass
B
MyClass
AnyObject
C
Any
MyClass
D
Any
AnyObject
Attempts:
2 left
💡 Hint
Remember that Any can hold any type, but type(of:) returns the actual type stored.
🧠 Conceptual
intermediate
2:00remaining
Difference between Any and AnyObject
Which statement correctly describes the difference between Any and AnyObject in Swift?
A<code>Any</code> can represent any type including value types; <code>AnyObject</code> can only represent class instances.
B<code>Any</code> and <code>AnyObject</code> are exactly the same and interchangeable.
C<code>AnyObject</code> can represent any type including value types; <code>Any</code> can only represent class instances.
D<code>Any</code> can only represent value types; <code>AnyObject</code> can only represent structs.
Attempts:
2 left
💡 Hint
Think about what kinds of types are classes and what kinds are value types in Swift.
🔧 Debug
advanced
2:00remaining
Why does this code cause a compile error?
Consider this Swift code: class Person {} let obj: AnyObject = Person() let num: AnyObject = 5 Why does the second assignment cause a compile error?
ABecause 5 is not initialized properly.
BBecause 5 is a value type (Int), and AnyObject can only hold class instances.
CBecause AnyObject cannot hold any type, only Any can.
DBecause Person is not a subclass of AnyObject.
Attempts:
2 left
💡 Hint
Remember what kinds of types are allowed in AnyObject.
📝 Syntax
advanced
2:00remaining
Which option correctly casts Any to a class type?
Given let anyVar: Any = MyClass(), which option safely casts anyVar to MyClass?
Aif let obj = anyVar as! MyClass? { print("Success") }
Bif let obj = anyVar as MyClass { print("Success") }
Cif let obj = anyVar is MyClass { print("Success") }
Dif let obj = anyVar as? MyClass { print("Success") }
Attempts:
2 left
💡 Hint
Think about safe optional casting syntax in Swift.
🚀 Application
expert
3:00remaining
Using Any and AnyObject in a heterogeneous collection
You want to create an array that can hold both class instances and value types. Which declaration allows this?
Avar mixedArray: [AnyObject] = [MyClass(), MyClass()]
Bvar mixedArray: [AnyObject] = ["Hello", 42, MyClass()]
Cvar mixedArray: [Any] = ["Hello", 42, MyClass()]
Dvar mixedArray: [Any] = [MyClass(), MyClass()]
Attempts:
2 left
💡 Hint
Remember which type can hold both value and reference types.