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 DoubleCreate a struct called
Circle that conforms to Shape and has a radius propertyCreate a function called
makeCircle that returns some Shape and returns a CirclePrint 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