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 instance2 var width: Double3 var height: Double4 // Computed property: no storage, the body runs on every read5 var area: Double { // Area = width × height6 return width * height7 }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 initializer14let rect = Rectangle(width: 5, height: 3)// Reads both computed properties: Area: 15.0, Perimeter: 16.015print("Area: \(rect.area), Perimeter: \(rect.perimeter)")Output
Area: 15.0, Perimeter: 16.0
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