0
0
Swiftprogramming~30 mins

Opaque types with some keyword in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Opaque Types with the some Keyword in Swift
📖 Scenario: Imagine you are building a simple app that shows different shapes. Each shape can tell its area, but you want to hide the exact type of shape from the user of your code. This helps keep your code clean and flexible.
🎯 Goal: You will create a function that returns a shape using Swift's some keyword to hide the exact type. Then you will print the area of the shape.
📋 What You'll Learn
Create a protocol called Shape with a property area of type Double
Create a struct called Circle that conforms to Shape and has a radius property
Create a function called makeCircle that returns some Shape and returns a Circle
Print the area of the shape returned by makeCircle
💡 Why This Matters
🌍 Real World
Opaque types are useful when you want to hide the exact type of a value but still guarantee it follows a certain interface. This is common in UI frameworks and libraries where you want to return views or shapes without exposing their concrete types.
💼 Career
Understanding opaque types and the <code>some</code> keyword is important for Swift developers working on apps or libraries. It helps write cleaner, safer, and more flexible code.
Progress0 / 4 steps
1
Create the Shape protocol and Circle struct
Create a protocol called Shape with a read-only property area of type Double. Then create a struct called Circle that conforms to Shape and has a property radius of type Double. Implement the area property to return the area of the circle using the formula 3.14159 * radius * radius.
Swift
Need a hint?

Remember, a protocol defines what properties or methods a type must have. The Circle struct must say it conforms to Shape and provide the area property.

2
Create the makeCircle function returning some Shape
Create a function called makeCircle that returns some Shape. Inside the function, return a Circle with a radius of 5.0.
Swift
Need a hint?

The some keyword hides the exact type but promises it conforms to Shape. Just return a Circle with radius 5.0.

3
Call makeCircle and store the result
Call the function makeCircle() and store the result in a constant called shape.
Swift
Need a hint?

Store the result of makeCircle() in a constant named shape.

4
Print the area of the shape
Print the area of the shape stored in shape using print("Area: \(shape.area)").
Swift
Need a hint?

Use print("Area: \(shape.area)") to show the area.