0
0
Swiftprogramming~30 mins

Any and AnyObject types in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Any and AnyObject Types in Swift
📖 Scenario: You are building a simple Swift program that stores different types of data in one place, like a mixed collection of items you might carry in a backpack.
🎯 Goal: Learn how to use Any and AnyObject types in Swift to hold different kinds of values and class instances, then check and print their types.
📋 What You'll Learn
Create an array called backpack that can hold values of any type using Any.
Create a class called Book with a property title.
Create an instance of Book and add it to the backpack.
Create an array called classItems that can hold only class instances using AnyObject.
Add the Book instance to classItems.
Use a for loop to check the type of each item in backpack and print a message describing the item.
💡 Why This Matters
🌍 Real World
In real apps, you often need to store mixed data types or class instances together, like user settings or UI elements.
💼 Career
Understanding <code>Any</code> and <code>AnyObject</code> helps you work with flexible data structures and APIs that accept multiple types.
Progress0 / 4 steps
1
Create a mixed array using Any
Create an array called backpack that can hold values of any type using Any. Add these exact items: the integer 5, the string "Water Bottle", and the boolean true.
Swift
Need a hint?

Use square brackets [] to create an array and specify the type as [Any].

2
Create a Book class and an instance
Create a class called Book with a property title of type String. Then create an instance called myBook with the title "Swift Programming".
Swift
Need a hint?

Define a class with a property and an initializer. Then create an instance using let.

3
Add the Book instance to backpack and create AnyObject array
Add the myBook instance to the backpack array. Then create an array called classItems of type [AnyObject] and add myBook to it.
Swift
Need a hint?

Use append() to add to the backpack array. Declare classItems as [AnyObject] and initialize it with myBook.

4
Check types and print descriptions
Use a for loop with variables item to go through each element in backpack. Inside the loop, use if let or is to check if item is an Int, String, Bool, or Book. Print exactly these messages for each type:
"Integer: <value>", "String: <value>", "Boolean: <value>", "Book title: <title>".
Swift
Need a hint?

Use as? to try casting item to each type and print the message if successful.