Computed Property in Swift

Level 3257 keystrokes

A Rectangle struct stores width and height and computes area and perimeter on each access. For a 5 × 3 rectangle it prints Area: 15.0, Perimeter: 16.0.

Swift code

1struct Rectangle {
// Stored properties: the values are kept in the instance
2 var width: Double
3 var height: Double
4
// Computed property: no storage, the body runs on every read
5 var area: Double {
// Area = width × height
6 return width * height
7 }
8
// Perimeter = 2 × (width + height)
9 var perimeter: Double {
10 return 2 * (width + height)
11 }
12}
13
// Creates a 5 × 3 rectangle with the memberwise initializer
14let rect = Rectangle(width: 5, height: 3)
// Reads both computed properties: Area: 15.0, Perimeter: 16.0
15print("Area: \(rect.area), Perimeter: \(rect.perimeter)")

Output

Area: 15.0, Perimeter: 16.0
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • :× 8
  • (× 5
  • )× 5
  • {× 3
  • }× 3
  • ,× 2
  • .× 2
  • "× 2
  • *× 2
  • \× 2

More Swift examples at level 3

← Swift typing practice