Computed Property in Swift

Level 3175 keystrokes

Defines a read-only computed property area that is calculated from the stored properties width and height each time it is read; prints "Area: 15.0".

Swift code

// A struct with stored and computed properties
1struct Rectangle {
// Stored properties: their values are kept in the instance
2 var width: Double
3 var height: Double
// A computed property has no storage; this block runs on every read
4 var area: Double {
// Returns width times height: 5.0 * 3.0 = 15.0
5 return width * height
6 }
7}
8
// The memberwise initializer takes only the stored properties
9let rect = Rectangle(width: 5.0, height: 3.0)
// Read like a normal property; a Double prints with .0: Area: 15.0
10print("Area: \(rect.area)")

Output

Area: 15.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.

  • :× 6
  • .× 3
  • (× 3
  • )× 3
  • "× 2
  • {× 2
  • }× 2
  • ,× 1
  • *× 1
  • \× 1

More Swift examples at level 3

← Swift typing practice