0
0
Swiftprogramming~15 mins

Computed properties in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Computed Properties in Swift
📖 Scenario: You are creating a simple app to manage rectangles. You want to store the width and height, and also calculate the area automatically whenever needed.
🎯 Goal: Build a Swift struct called Rectangle with stored properties for width and height, and a computed property for area.
📋 What You'll Learn
Create a struct named Rectangle
Add stored properties width and height of type Double
Add a computed property area that returns the product of width and height
Create an instance of Rectangle with width 5.0 and height 3.0
Print the area of the rectangle
💡 Why This Matters
🌍 Real World
Computed properties help keep data consistent and up-to-date without storing extra values. For example, calculating area or volume on demand.
💼 Career
Understanding computed properties is essential for Swift developers building apps that manage dynamic data efficiently.
Progress0 / 4 steps
1
Create the Rectangle struct with width and height
Create a struct called Rectangle with two stored properties: width and height, both of type Double. Set no initial values.
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.
Swift
Need a hint?

Computed properties use { return ... } to calculate values on the fly.

3
Create an instance of Rectangle
Create a constant called myRect and assign it a 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 rectangle.

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

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