0
0
Swiftprogramming~10 mins

Any and AnyObject types in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a variable that can hold any type of value.

Swift
var value: [1]
Drag options to blanks, or click blank then click option'
AObject
BAnyObject
CAny
DNSObject
Attempts:
3 left
💡 Hint
Common Mistakes
Using AnyObject which only holds class instances.
Using NSObject which is a specific class, not a type alias.
2fill in blank
medium

Complete the code to declare a variable that can hold any class instance.

Swift
var object: [1]
Drag options to blanks, or click blank then click option'
AAny
BAnyObject
CNSObject
DObject
Attempts:
3 left
💡 Hint
Common Mistakes
Using Any which can hold any value, not just class instances.
Using NSObject which is a specific class, not a type alias.
3fill in blank
hard

Fix the error in the code by choosing the correct type for the array that holds any kind of value.

Swift
let items: [[1]] = [42, "Swift", 3.14]
Drag options to blanks, or click blank then click option'
AAny
BAnyObject
CNSObject
DObject
Attempts:
3 left
💡 Hint
Common Mistakes
Using AnyObject which only holds class instances, not value types like Int or Double.
4fill in blank
hard

Fill both blanks to create a function that accepts any class instance and prints its description.

Swift
func describe(object: [1]) {
    print(object[2])
}
Drag options to blanks, or click blank then click option'
AAnyObject
BAny
C.description
D.debugDescription
Attempts:
3 left
💡 Hint
Common Mistakes
Using Any as parameter type which accepts all types, but the function expects class instances.
Using .debugDescription which is less common for simple descriptions.
5fill in blank
hard

Fill both blanks to create a function that takes Any and returns the description if it's a class instance.

Swift
func getDescription(_ value: [1]) -> String? {
    guard let obj = value as? [2] else { return nil }
    return obj.description
}
Drag options to blanks, or click blank then click option'
AAny
BAnyObject
CNSObject
DObject
Attempts:
3 left
💡 Hint
Common Mistakes
Using AnyObject for the parameter prevents passing non-class values.
Using NSObject which is too specific and doesn't cover all classes.