0
0
Swiftprogramming~15 mins

Adding computed properties in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Adding computed properties
📖 Scenario: You are creating a simple app to manage rectangles. Each rectangle has a width and height. You want to add a property that calculates the area automatically.
🎯 Goal: Build a Swift struct called Rectangle with stored properties for width and height, and add a computed property called area that calculates the rectangle's area.
📋 What You'll Learn
Create a struct named Rectangle with two stored properties: width and height of type Double.
Add a computed property called area that returns the product of width and height.
Create an instance of Rectangle with width 5.0 and height 3.0.
Print the value of the area property.
💡 Why This Matters
🌍 Real World
Computed properties help keep data consistent and avoid manual calculations in apps that manage shapes, sizes, or any related data.
💼 Career
Understanding computed properties is essential for Swift developers building iOS apps, as it helps write clean, efficient, and maintainable code.
Progress0 / 4 steps
1
Create the Rectangle struct with width and height
Create a Swift struct called Rectangle with two stored properties: width and height, both of type Double. Do not add any methods or computed properties yet.
Swift
Need a hint?

Use struct Rectangle { var width: Double; var height: Double } to define the shape.

2
Add a computed property for area
Inside the Rectangle struct, add a computed property called area of type Double that returns the product of width and height. Use the var area: Double { ... } syntax.
Swift
Need a hint?

Computed properties use var area: Double { return width * height }.

3
Create a Rectangle instance
Create a constant called myRect and assign it a new Rectangle instance with width 5.0 and height 3.0.
Swift
Need a hint?

Use let myRect = Rectangle(width: 5.0, height: 3.0) to create the instance.

4
Print the area of the rectangle
Write a print statement to display the value of myRect.area.
Swift
Need a hint?

Use print(myRect.area) to show the area.