0
0
Swiftprogramming~15 mins

Is operator for type checking in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Is operator for type checking
📖 Scenario: Imagine you are building a simple app that handles different types of pets. You want to check the type of each pet to perform specific actions.
🎯 Goal: You will create a list of pets with different types, then use the is operator to check each pet's type and count how many pets are dogs.
📋 What You'll Learn
Create an array called pets containing different pet types
Create a variable called dogCount to count dogs
Use a for loop with is operator to check if a pet is a dog
Print the total number of dogs using print
💡 Why This Matters
🌍 Real World
Type checking helps apps handle different data safely, like distinguishing between pet types to show correct info.
💼 Career
Understanding type checking is important for Swift developers to write safe and bug-free code, especially when working with mixed data.
Progress0 / 4 steps
1
Create the pets array
Create an array called pets containing these exact values: "Dog", "Cat", "Dog", "Bird", "Dog".
Swift
Need a hint?

Use square brackets [] to create an array and separate values with commas.

2
Create the dogCount variable
Create a variable called dogCount and set it to 0 to count the number of dogs.
Swift
Need a hint?

Use var to create a variable that can change.

3
Use the is operator to count dogs
Use a for loop with the variable pet to iterate over pets. Inside the loop, use the is operator to check if pet is String and equals "Dog". If yes, increase dogCount by 1.
Swift
Need a hint?

Use for pet in pets to loop. Use if pet is String && pet == "Dog" to check type and value.

4
Print the number of dogs
Write print("Number of dogs: \(dogCount)") to display the total number of dogs counted.
Swift
Need a hint?

Use print with string interpolation to show the count.