0
0
Swiftprogramming~30 mins

Existential types (any keyword) in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Existential Types with the any Keyword in Swift
📖 Scenario: Imagine you are building a simple app that manages different types of shapes. Each shape can tell its area, but the shapes are different types. You want to store them together and work with them in a common way.
🎯 Goal: You will create a protocol for shapes, then use the any keyword to hold different shapes in one list. Finally, you will calculate and print the area of each shape.
📋 What You'll Learn
Create a protocol called Shape with a property area of type Double
Create two structs Circle and Rectangle that conform to Shape
Create a variable shapes that holds an array of any Shape
Use a for loop to print the area of each shape
💡 Why This Matters
🌍 Real World
Using existential types with the <code>any</code> keyword helps you write flexible code that can work with different types sharing common behavior, like shapes in a drawing app.
💼 Career
Understanding existential types is important for Swift developers to handle collections of different types safely and clearly, which is common in app development and frameworks.
Progress0 / 4 steps
1
Create the Shape protocol and two shape structs
Create a protocol called Shape with a read-only property area of type Double. Then create two structs called Circle and Rectangle that conform to Shape. Circle should have a property radius of type Double, and Rectangle should have properties width and height of type Double. Implement the area property for both structs to calculate the correct area.
Swift
Need a hint?
Remember, a protocol defines a property called area. The structs must calculate area using the formulas for circle and rectangle.
2
Create an array of any Shape
Create a variable called shapes that holds an array of any Shape. Initialize it with a Circle of radius 3.0 and a Rectangle of width 4.0 and height 5.0.
Swift
Need a hint?
Use the syntax [any Shape] to hold different shapes in one array.
3
Loop over shapes and print their areas
Use a for loop with the variable shape to iterate over shapes. Inside the loop, print the area of each shape using print("Area: \(shape.area)").
Swift
Need a hint?
Use a for loop to go through each shape and print its area.
4
Print the areas of all shapes
Run the program to print the area of each shape in the shapes array. The output should show the area of the circle and the rectangle.
Swift
Need a hint?
The program should print the area of the circle (about 28.27) and the rectangle (20.0).