Menu
CoddyTech

Stored and Computed Properties

Lesson 27 of 48 in Coddy's Swift for Dart Developers course.

Dart getters and Swift computed properties run code when accessed. A stored property retains data; a computed property derives it from current state. Swift structs usually receive a memberwise initializer when no custom initializer suppresses it. Dart constructors must be declared explicitly for the fields you initialize. A read-only computed property has no setter, which does not make all its dependencies immutable. Here a temperature getter converts Celsius to Fahrenheit and reflects a later mutation of the stored temperature.

Complete Dart program. Each labelled block is a separate file.

Temperature.dart

class Temperature {
  int celsius;
  Temperature(this.celsius);
  int get fahrenheit => celsius * 9 ~/ 5 + 32;
}

main.dart

import 'Temperature.dart';
void main() {
  final reading = Temperature(0);
  print(reading.fahrenheit);
  reading.celsius = 100;
  print(reading.fahrenheit);
}

Complete Swift program. Each labelled block is a separate file.

Temperature.swift

import Foundation
struct Temperature {
    var celsius: Int
    var fahrenheit: Int { celsius * 9 / 5 + 32 }
}

main.swift

import Foundation
var reading = Temperature(celsius: 0)
print(reading.fahrenheit)
reading.celsius = 100
print(reading.fahrenheit)
challenge icon

Challenge

Easy

Implement Rectangle with mutable integer width and height, memberwise initializer, and computed area: Int. Area is width times height and must reflect later mutations. Input is width, height, then replacement width, each 1 through 100. Output area before and after the replacement.

Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.

Your code goes in Rectangle.swift, Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

import Foundation
func apiChecks(_ input: String) -> Bool {
var r = Rectangle(width: 6, height: 7); guard r.area == 42 else { return false }; r.height = 2; return r.area == 12
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for Dart Developers

Practice on your own: Swift playground