0
0
Swiftprogramming~30 mins

Type constraints with protocol conformance in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Type constraints with protocol conformance
📖 Scenario: You are building a simple system to handle different shapes and calculate their areas. Each shape must follow a common rule to provide its area.
🎯 Goal: Create a protocol called Shape with a property for area. Then, create two structs that conform to this protocol. Finally, write a generic function that only accepts types conforming to Shape and prints their area.
📋 What You'll Learn
Create a protocol named Shape with a read-only property area of type Double
Create a struct Square that conforms to Shape with a sideLength property
Create a struct Circle that conforms to Shape with a radius property
Write a generic function printArea that accepts a parameter constrained to Shape and prints its area
💡 Why This Matters
🌍 Real World
Protocols and type constraints help write flexible and reusable code that works with many types sharing common behavior.
💼 Career
Understanding protocol conformance and generics is essential for Swift developers building scalable and maintainable apps.
Progress0 / 4 steps
1
Create the Shape protocol
Create a protocol called Shape with a read-only property area of type Double.
Swift
Need a hint?

Protocols define a blueprint. Use var area: Double { get } to declare a read-only property.

2
Create Square and Circle structs conforming to Shape
Create a struct called Square with a sideLength property of type Double. Make it conform to Shape by implementing the area property as sideLength squared. Also, create a struct called Circle with a radius property of type Double. Make it conform to Shape by implementing the area property as π times radius squared.
Swift
Need a hint?

Use struct Name: Shape to conform. Calculate area inside a computed property.

3
Write a generic function with type constraint
Write a generic function called printArea that accepts one parameter named shape of generic type T. Add a type constraint so that T must conform to the Shape protocol. Inside the function, print the area of the shape using print("Area: \(shape.area)").
Swift
Need a hint?

Use func printArea<T: Shape>(shape: T) to add the type constraint.

4
Call printArea with Square and Circle instances
Create a constant square of type Square with sideLength 4.0. Create a constant circle of type Circle with radius 3.0. Call printArea with square and then with circle.
Swift
Need a hint?

Create instances with the exact property values and call printArea with them.